Я написал макрос VBA для импорта многих текстовых файлов (из 1 папки) на отдельные листы в 1 книге Excel. Все файлы читаются в каждом отдельном листе просто отлично. Однако я вижу проблему размещения на местах. Заголовки в каждом текстовом файле одинаковы. Но сами значения полей иногда подталкиваются несколькими полями. Таким образом, не все значения полей выстраиваются под соответствующие заголовки. Может ли кто-нибудь предложить мне, почему это происходит? Я пробовал посмотреть, есть ли табуляция с разделителями табуляции или проблема с ограничением по каналам, но это, похоже, не проблема.Импорт нескольких текстовых файлов в отдельные листы Excel в 1 книге Excel с использованием VBA
Sub MultipleTextFilesIntoExcelSheets()
Dim i As Integer 'a counter to loop through the files in the folder
Dim fname As String, FullName As String 'fname is the name of the file, and FullName is the name of its path
Dim ws As Worksheet 'a workbook object for the workbook where the current macro is running
i = 0 'seed the counter
'get the name of the first text file
fname = Dir("C:\dummy_path\*txt")
'loop through the text files to put them onto separate sheets in the Excel book
While (Len(fname) > 0)
'get the full path of the text file
FullName = "C:\dummy_path\" & fname
i = i + 1 'get ready for the next iteration
Set ws = ThisWorkbook.Sheets("Sheet" & i) 'the current sheet
With ws.QueryTables.Add(Connection:="TEXT;" & FullName, Destination:=ws.Range("A1"))
.Name = "a" & i
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True 'we are using a tab-delimited file
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
fname = Dir
End With
Wend
End Sub
VBA обрабатывает букву «f» в качестве разделителя табуляции. Кто-нибудь знает, почему и как это исправить? – user3100444
Любая идея, почему я получаю ошибку «Subscript out of range» при запуске этого кода? Он импортирует первый файл txt в тот же лист, что и моя кнопка макроса, затем ошибка в этой строке 'Set ws = ThisWorkbook.Sheets (« Sheet »& i)' –
Просто нашел этот код, который работает очень хорошо, и метки каждый лист с именем файла txt [label-sheets-while-importing-multiple-text-files-excel-vba] (http://stackoverflow.com/questions/17891733/label-sheets-while-importing-multiple-text- files-excel-vba) –