VBA读取txt 遇到某行一样的数据把子行所有数据整合一起
时间: 2023-06-12 21:02:16 浏览: 170
,该怎么做?
对于这个问题,可以使用VBA读取txt文件,并使用循环语句遍历每一行数据。当遇到某行与之前的某行相同时,使用字符串拼接操作将子行数据整合在一起,最终将整合后的数据输出为新的txt文件。以下是示例代码供参考:
Sub MergeRows()
Dim FilePath As String
FilePath = "C:\test.txt" 'txt文件路径
Dim NewFilePath As String
NewFilePath = "C:\newtest.txt" '新txt文件路径
Dim FSO As Scripting.FileSystemObject
Set FSO = New Scripting.FileSystemObject
Dim OpenFile As Scripting.TextStream
Set OpenFile = FSO.OpenTextFile(FilePath, ForReading, False, TristateUseDefault) '打开txt文件
Dim OpenNewFile As Scripting.TextStream
Set OpenNewFile = FSO.CreateTextFile(NewFilePath, True, False) '创建新txt文件
Dim PreLine As String
Dim CurLine As String
Dim MergeText As String
Dim MergeFlag As Boolean
PreLine = ""
MergeText = ""
MergeFlag = False
Do Until OpenFile.AtEndOfStream
CurLine = OpenFile.ReadLine '读取一行数据
If CurLine = PreLine And PreLine <> "" Then '如果当前行与之前行相同
MergeText = MergeText & vbCrLf & CurLine '使用字符串拼接将子行数据整合在一起
MergeFlag = True
ElseIf MergeFlag = True Then
OpenNewFile.WriteLine MergeText '将整合后的数据输出到新txt文件
MergeText = ""
MergeFlag = False
Else
OpenNewFile.WriteLine PreLine '将上一行数据输出到新txt文件
End If
PreLine = CurLine
Loop
OpenNewFile.WriteLine PreLine '最后一行数据需要单独处理
OpenFile.Close '关闭文件
OpenNewFile.Close
End Sub
阅读全文