首页 > 解决方案 > 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 个不同系统上进行了尝试。结果相同。

标签: excelvbaexcel-2016

解决方案


我不是主题专家,但通过查看文档,我认为您应该在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

推荐阅读