运行时错误1004 excel无法找到文本文件来刷新此外部范围

时间:2017-03-30 13:33:55

标签: excel vba excel-vba excel-2010 excel-2007

我正在尝试将文件夹中的tsv文件转换为xlsx格式,方法是使用Data => From Text选项通过VBA将它们导入为文本文件。

在此期间遇到此错误

enter image description here

enter image description here

代码:

Sub convert()

Dim CSVfolder As String, XlsFolder As String, fname As String, wBook As Workbook

CSVfolder = ActiveSheet.Range("B2").Value & "\"

fname = Dir(CSVfolder & "*.tsv")

Do While fname <> ""
    Workbooks.Add
    
    Set wBook = ActiveWorkbook
    
       With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fname, Destination:=Range("$A$1"))
        .Name = fname
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 65001
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierNone
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
   
    wBook.Close False
    fname = Dir
    
 Loop
End Sub

End Sub

为什么我在 .Refresh BackgroundQuery:= False 中收到错误?

1 个答案:

答案 0 :(得分:2)

错误发生在那里,因为它在Refresh阶段寻找文件。

问题是Fname不会包含路径。

将您的连接更改为:

With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & CSVfolder & fname, Destination....