简体   繁体   中英

Extract a string from a multiline string

VBA read the below from a text and assigns it into a variable. I need to extract the Name (in this example, it would be "Canada, Ontraio") from it. But the text will contain more than one occurrences of this "Name" and I should be able to assign each name into an array to re-call it later.

ID         = abc123    NAME       = Canada, Ontario                      
NT         = U         SIZE       =      0       BYTES                             
DT ID      = 5A        DEP        =  D E

below is the code to read it from the text file:

Set oFS = oFSO.OpenTextFile("c:\\users\test.txt")
txtpro = oFS.ReadAll

If InStr(strarray(intCount), "TYPE") Then
  UserName() = Split(strarray(intCount), "TYPE")
End If

If Not (Not UserName()) Then
    For TotUName = LBound(UserName()) To UBound(UserName())
       Debug.Print UserName(TotUName)
    Next
End if

I am assuming that you know how to loop through lines in a file.

Try this

'~~> Sample String
s = "ID         = abc123    NAME       = Canada, Ontario"
MyAr = Split(s, "=")

'~~> Check if you have " NAME " in MyAr(UBound(MyAr) - 1)
If InStr(1, MyAr(UBound(MyAr) - 1), " NAME ", vbTextCompare) Then
    Debug.Print MyAr(UBound(MyAr))
End If

The above will give you Canada, Ontario . The below will give you nothing

s = "NT         = U         SIZE       =      0       BYTES     "
MyAr = Split(s, "=")

If InStr(1, MyAr(UBound(MyAr) - 1), " NAME ", vbTextCompare) Then
    Debug.Print MyAr(UBound(MyAr))
End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM