我的目标是将文件夹中的txt文件导出并合并到一个Excel工作表中,并分别在单独的列中获取文件名和txt文件的保存日期。
在尝试通过以下代码合并excel文件夹中的txt文件时,我在 .Refresh BackgroundQuery:= True 中收到运行时错误1004我为什么会收到错误?
Sub test()
Dim wbk As Workbook, wksht As Worksheet
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xFiles As New Collection
Dim I As Long
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
xFile = Dir(xStrPath & "*.txt")
If xFile = "" Then
MsgBox "No files found", vbInformation, "eBay"
Exit Sub
End If
Workbooks.Add
Set wbk = ActiveWorkbook
Set wksht = ActiveSheet
Do While xFile <> ""
xFiles.Add xFile, xFile
xFile = Dir()
Loop
If xFiles.Count > 0 Then
For I = 1 To xFiles.Count
'On Error Resume Next
With wksht.QueryTables.Add(Connection:="TEXT;" & xFile, Destination:=Range("$A$1"))
.Name = xFile
.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:=True
End With
Next
End If
End Sub
还有其他简单方法吗?
答案 0 :(得分:2)
这是解决方法,谢谢大家的帮助:)
With wksht.QueryTables.Add(Connection:="TEXT;" & xStrPath & xFiles.Item(I), Destination:=Range("$A$1"))
.Name = xFiles.Item(I)