【发布时间】:2014-01-29 16:38:48
【问题描述】:
我编写了一个 VBA 宏,用于将许多文本文件(来自 1 个文件夹)导入到 1 个 Excel 工作簿中的单独工作表中。所有文件都读入每个单独的工作表就好了。但是,我看到了字段放置问题。每个文本文件的标题都是相同的。但是,字段值本身有时会被一些字段压低。因此,并非所有字段值都在其正确的标题下排列。有人可以向我建议为什么会这样吗?我试过看看它是制表符分隔的还是竖线分隔的问题,但这似乎不是问题。
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
结束子
【问题讨论】:
-
VBA 将字母“f”视为制表符分隔符。有人知道为什么或如何解决它吗?
-
知道为什么我在运行此代码时会收到“下标超出范围”错误吗?它确实将第一个 txt 文件导入到与我的宏按钮相同的工作表中,然后在这一行出现错误
Set ws = ThisWorkbook.Sheets("Sheet" & i) -
刚刚发现这段代码非常好用,并用txt文件名label-sheets-while-importing-multiple-text-files-excel-vba标记每张纸