excel - Excel VBA 文本文件导入为空白
问题描述
我正在尝试将 800 多个文本文件导入到同一工作簿中自己的工作表中。代码如下:
Public Sub dImport()
nFile = Dir("R:\O21DIR\*.txt")
Do While nFile <> vbNullString
Set ws3 = Sheets.Add(After:=Sheets(Sheets.Count))
Application.CutCopyMode = False
With ws3.QueryTables.Add(Connection:="TEXT;" & nFile, Destination:=Range("$A$1"))
.Name = nFile
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 9, 9, 2, 9, 2, 9, 9, 9)
.TextFileFixedColumnWidths = Array(21, 16, 10, 13, 17, 3, 14, 7, 5, 12, 5, 6)
.TextFileTrailingMinusNumbers = True
End With
ws3.Name = nFile
For cnt = ActiveWorkbook.Connections.Count To 1 Step -1
ActiveWorkbook.Connections.Item(cnt).Delete
Next
For cnt = ActiveWorkbook.Queries.Count To 1 Step -1
ActiveWorkbook.Queries.Item(cnt).Delete
Next
nFile = Dir
fRefine
Loop
End Sub
我没有得到任何错误,但我也没有得到任何东西。工作表已正确创建和命名。并且文本文件中确实有数据。数据导入代码是从录制宏中提取的,因此它在某一时刻确实有效。
我确实删除了,.Refresh BackgroundQuery:=False
因为我收到了错误 1004。
我错过了什么/做错了什么?
在 Office 365 32 位上使用 Excel 2016。我已经在具有相同软件设置的 2 个不同系统上进行了尝试。结果相同。
解决方案
我不是主题专家,但通过查看文档,我认为您应该在Refresh
某个地方添加一个。
从上面的页面粘贴:
Set shFirstQtr = Workbooks(1).Worksheets(1)
Set qtQtrResults = shFirstQtr.QueryTables.Add( _
Connection := "TEXT;C:\My Documents\19980331.txt", _
Destination := shFirstQtr.Cells(1,1))
With qtQtrResults
.TextFileParsingType = xlFixedWidth
.TextFileFixedColumnWidths := Array(5,4)
.TextFileColumnDataTypes := _
Array(xlTextFormat, xlSkipColumn, xlGeneralFormat)
.Refresh
End With
推荐阅读
- mysql - MySQL 在连接表上应用过滤器
- php - php://output - Only output part of page and not whole page
- reactjs - Mutate multiple states from within useEffect causes react-hooks/exhaustive-deps warning
- java - NetBeans/Java - 断点无法捕获异常
- mysql - 返回混合的非系列项目 + 下一个即将推出的系列
- symfony - Symfony 和 NLTK
- django - AssertionError: You need to pass a valid Django Model in UserProfile.Meta, received "None"
- r - x.ar 对 R 变量 x 意味着什么?
- wizard - 来自向导的 Odoo 12 确认表(确认/丢弃)
- java - 将 Spring Boot Starter Web 依赖项与 Mongo Driver 3.11.0 一起使用时出现 java.lang.NoSuchMethodError