我正在尝试将文件夹中的tsv文件转换为xlsx格式,方法是使用Data => From Text选项通过VBA将它们导入为文本文件。
在此期间遇到此错误
代码:
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 中收到错误?
答案 0 :(得分:2)
错误发生在那里,因为它在Refresh
阶段寻找文件。
问题是Fname
不会包含路径。
将您的连接更改为:
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & CSVfolder & fname, Destination....