Vba 如何读取txt文件中的行,但从第二行开始,跳过第一行?
因此,此Excel宏在从特定文件夹读取多个txt文件并将所有行插入第一张Excel工作表时非常有效。我想编辑此代码,以便宏跳过每个txt文件的第一行 有人能帮忙吗Vba 如何读取txt文件中的行,但从第二行开始,跳过第一行?,vba,excel,Vba,Excel,因此,此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 S
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
选项1预先读取第一行 在开始Do While循环之前,请添加以下行:
If Not FileText.AtEndOfStream Then TextLine = FileText.ReadLine
这样,您将读取第一行(如果有的话),而Do-While循环将只读取后续的行
选项2删除excel中的第一行
另一个解决方案是在脚本导入完所有文件后删除excel中的第一行
您可能必须明确这适用于哪些列,因为我不确定活动导入是否是唯一一个(否则,您将删除以前导入的、根本不应删除的值!为什么要循环遍历文本文件中的每一行?这会降低代码的速度。以数组形式一次性读取文件,然后循环遍历数组。这样,您就可以轻松跳过所需的任何行。请参阅