【发布时间】:2013-05-01 00:15:46
【问题描述】:
因此,此 Excel 宏非常适合从特定文件夹读取多个 txt 文件并将所有行插入第一个 Excel 工作表中。我想编辑此代码以使宏跳过每个 txt 文件的第一行..
谁能帮忙?
Sub test1()
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:\Users\Desktop\TXT")
' 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 | delimited pieces
Items = Split(TextLine, vbTab)
' Put data on one row in active sheet
cl.Value = file.Name
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, i + 1).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
【问题讨论】:
-
为什么要遍历文本文件中的每一行?这会减慢你的代码。一口气读取数组中的文件,然后循环遍历数组。这样你就可以轻松地跳过你想要的任何一行。见THIS