My target is to export txt files in a folder and consolidate it into one excel sheet also get the file name and the saved date of the txt files in separate column respectively.
While trying to consolidate txt files in a folder in excel by below code, I'm getting a runtime error 1004 in .Refresh BackgroundQuery:=True why I'm getting the error?
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
Is there any other simple way?