Excel VBA文本文件导入为空

时间:2018-12-20 16:27:44

标签: excel-vba excel-2016

我正在尝试将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

我没有收到任何错误,但是在工作表上什么也没得到。工作表已创建并正确命名。文本文件中确实有数据。数据导入代码是从录制宏中提取的,因此DID可以在某一时刻工作。

我确实删除了.Refresh BackgroundQuery:=False,因为遇到了错误1004。

我缺少什么/做错了什么?

在32位Office 365上使用Excel 2016。我已经在具有相同软件设置的2个不同系统上进行了尝试。结果相同。

1 个答案:

答案 0 :(得分:0)

我不是主题专家,但是通过查看the documentation,我认为您应该在某处添加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