读取.txt文件并将某些数据复制/粘贴到满足一定条件的Excel

文件sample.txt

 某物  
 ------
 --------
 ------

 XYZ

 12 34 56
 78 90 10
 11 12 1ds3
 14 15 16 17

 ABC

某物  
 ------
 --------
 ------

 XYZ

 14 34 566
 785 490 10
 113 142 1ds3
 143 155 616 17

 ABC 

现在我想写一个VBScript来读取sample.txt ,只复制xyzabc之间的数据。

我尝试了以下内容:

 Sub test1() Dim fso As FileSystemObject Dim strMerge As String Set fso = New FileSystemObject Set txtStream = fso.OpenTextFile("filepath", ForReading, False) Do While txtStream.AtEndOfStream <> True If InStr(txtStream.ReadLine, "xyz") <> 0 Then strMerge = strMerge & txtStream.ReadLine Do While Not InStr(txtStream.ReadLine, "abc") <> 0 strMerge = strMerge + txtStream.ReadLine Loop Else strMerge = strMerge & txtStream.ReadLine End If Next i Loop MsgBox (strMerge) txtStream.Close End Sub 

使用RegEx的解决scheme

 Sub test1() Dim fso As FileSystemObject Dim strMerge As String Dim txtStream As Variant Dim textLine As String Set fso = New FileSystemObject Set txtStream = fso.OpenTextFile("C:\Users\pankaj.jaju\Desktop\test.txt", ForReading, False) txt = txtStream.ReadAll Dim objRegEx, oRegResults Set objRegEx = CreateObject("VBScript.RegExp") With objRegEx .IgnoreCase = True .MultiLine = True .Global = True .Pattern = "xyz\s*([\S\s]*?)\s*?\S*?abc" End With Set oRegResults = objRegEx.Execute(txt) For Each txtMatch In oRegResults MsgBox txtMatch.Submatches(0) Next txtStream.Close End Sub 

假设你不想在这里读XYZ和ABC,你就去。

 Sub test1() Dim ReadEn As Boolean Dim fso As FileSystemObject Dim strMerge As String Dim tStr As String Set fso = New FileSystemObject Set txtStream = fso.OpenTextFile("c:\projects\sample.txt", ForReading, False) ReadEn = False Do While txtStream.AtEndOfStream <> True tStr = txtStream.ReadLine If InStr(tStr, "abc") > 0 Then ReadEn = False ' do not read "xyz" If ReadEn Then strMerge = strMerge & tStr & Chr(13) End If If InStr(tStr, "xyz") > 0 Then ReadEn = True Loop MsgBox (strMerge) txtStream.Close End Sub 

我打开ReadEn启用阅读文件到tStr我不ReadLine因为我可能通过EOF,而仍然在循环中。 不知道是否也想读取空格,但是会被读取和输出。 如果你想输出xyzabc sawp他们的if语句的位置。

有:

  • next i不是“范围之内”

  • Readline()处理每两行跳过txt文件

尝试这个

 Option Explicit Sub test1() Dim fso As FileSystemObject Dim strMerge As String Dim txtStream As Variant Dim textLine As String Set fso = New FileSystemObject Set txtStream = fso.OpenTextFile("filepath", ForReading, False) Do While txtStream.AtEndOfStream <> True textLine = txtStream.ReadLine If InStr(textLine, "xyz") <> 0 Then textLine = txtStream.ReadLine Do While Not InStr(textLine, "abc") <> 0 strMerge = strMerge & textLine textLine = txtStream.ReadLine Loop End If Loop MsgBox strMerge txtStream.Close End Sub 

当然你必须把“filepath”改成一个连接所需txt文件实际完整path的string

只要使用一些一次性物品和放置好的分割。

 Sub test1() Dim ecA, ec(): ReDim ec(0) ecA = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\testenv\test.txt", 1).ReadAll, "xyz") For I = 1 To UBound(ecA): ec(UBound(ec)) = Split(ecA(I), "abc")(0): ReDim Preserve ec(UBound(ec) + 1): Next ReDim Preserve ec(UBound(ec) - 1) End Sub