在 Excel 2010 中,我想将文件夹中的所有文本文件数据加载到一个工作表中。
每张表应该有一个文本文件的数据。
每张纸都是用第一行上的标题分隔的管道。
更新宏
Sub LoadTextFilesLoop()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim ws As Worksheet
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object associated with the directory
Set objFolder = objFSO.GetFolder("C:\Export\")
'Loop through the Files collection
For Each objFile In objFolder.Files
NewFileImport (objFile.Name)
Next
'Clean up!
Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
End Sub
Sub NewFileImport(FileName)
Sheets.Add After:=Sheets(Sheets.Count)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Export\FileName", _
Destination:=Range("$A$1"))
.Name = FileName
.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 = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "|"
.TextFileColumnDataTypes = Array(1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
循环没有加载数据。
我仍然必须弄清楚如何获得每个文件中的列数。
.TextFileColumnDataTypes = Array(1, 1, 1)
这一行告诉这个文件中的三列。这应该根据文件列而有所不同。