我试图将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。我在使用相同软件设置的两个不同系统上尝试了此操作。相同的结果。
我不是主题专家,但是通过查看文档,我认为您应该在某个地方添加Refresh
。
从上页粘贴:
Set shFirstQtr = Workbooks(1).Worksheets(1)
Set qtQtrResults = shFirstQtr.QueryTables.Add( _
Connection := "TEXT;C:My Documents19980331.txt", _
Destination := shFirstQtr.Cells(1,1))
With qtQtrResults
.TextFileParsingType = xlFixedWidth
.TextFileFixedColumnWidths := Array(5,4)
.TextFileColumnDataTypes := _
Array(xlTextFormat, xlSkipColumn, xlGeneralFormat)
.Refresh
End With