档案sample.txt
:
something ------ -------- ------ xyz 12 34 56 78 90 10 11 12 1ds3 14 15 16 17 abc something ------ -------- ------ xyz 14 34 566 785 490 10 113 142 1ds3 143 155 616 17 abc
现在我想编写一个VBScript来阅读sample.txt
并仅复制介于xyz
和abc
之间的数据。
我尝试了以下内容:
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
答案 0 :(得分:2)
使用RegEx的解决方案
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
答案 1 :(得分:1)
假设你不想在这里阅读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。
不确定您是否也想读取空白,但它们将被读取和输出。如果您想输出xyz
和abc
,请查看其if语句的位置。
答案 2 :(得分:1)
有:
next i
不在&#34;范围&#34;
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
当然你必须改变&#34; filepath&#34;到一个字符串,包含所需的txt文件的实际完整路径
答案 3 :(得分:0)
只需使用一些一次性物品和放置好的分裂物即可。
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