我找到了将大量文本文件中的数据行导入Excel工作表的答案(由Chris Neilsen回答https://stackoverflow.com/a/4941605/1892030)。不过我还想做以下事情:
克里斯的答案提到上面的工作真的很好,所以我想编辑代码以允许我在上面第1点和第3点的额外要求 - 但不知道如何。为了完整起见,我复制了下面前面的答案中的代码。非常感谢。
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("C:\#test")
' set the starting point to write the data to
Set cl = ActiveSheet.Cells(1, 1)
' Loop thru all files in the folder
For Each file In folder.Files
' Open the file
Set FileText = file.OpenAsTextStream(ForReading)
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
' Parse the line into comma delimited pieces
Items = Split(TextLine, ",")
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, i).Value = Items(i)
Next
' Move to next row
Set cl = cl.Offset(1, 0)
Loop
' Clean up
FileText.Close
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
答案 0 :(得分:0)
我还没有为你完成这一切(我希望文件名需要整理以适应你想要的格式),但是请放下这些代码,它会让你开始......
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
' Process lines which don't begin with Asterisk (*)
If Left(TextLine,1)<>"*" Then
' This crudely appends the filename as if it were a column in the source file
TextLine = TextLine + "," + file.Name
' Parse the line into comma delimited pieces
Items = Split(TextLine, ",")
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, i).Value = Items(i)
Next
' Move to next row
Set cl = cl.Offset(1, 0)
End If
Loop