gpt4 book ai didi

vba - 如何读取 txt 文件中的行,但从第二行开始,跳过第一行?

转载 作者:行者123 更新时间:2023-12-04 20:18:10 25 4
gpt4 key购买 nike

因此,此 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

最佳答案

选项 1 预先阅读第一行

在开始 Do While 循环之前,请添加以下行:

If Not FileText.AtEndOfStream Then TextLine = FileText.ReadLine

这样,您将读取第一行(如果有),而您的 Do While 循环将仅读取后续行

选项 2 之后删除 excel 中的第一行

另一种解决方案可能是在脚本完成导入所有文件后删除 excel 中的第一行。

您可能必须具体说明这适用于哪些列,因为我不确定事件导入是否是唯一的(否则您将删除以前导入的根本不应该删除的值!

关于vba - 如何读取 txt 文件中的行,但从第二行开始,跳过第一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16304282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com