【发布时间】:2017-05-21 06:10:01
【问题描述】:
我的目标是导出文件夹中的txt文件并将其合并到一个excel表中,并分别在单独的列中获取txt文件的文件名和保存日期。
在尝试通过以下代码将 txt 文件合并到 excel 中的文件夹中时,我在 .Refresh BackgroundQuery:=True 中收到运行时错误 1004,为什么会收到此错误? p>
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
还有其他简单的方法吗?
【问题讨论】:
-
你在哪一行得到错误?
-
@DavidG 在这一行 .Refresh BackgroundQuery:=True
-
是的,我应该使用 With wksht.QueryTables.Add(Connection:="TEXT;" & xStrPath & xFiles.Item(I), Destination:=Range("$A$1")) 和.Name = xFiles.Item(I)