我想知道是否有辦法通過指定開始的幾個字符和結束字符來提取子字符串的字符串。通過指定子字符串的第一個和最後一個字符串來提取字符串中的子字符串
作爲一個例子,我在工作簿中的單元格中有類似於問題底部的字符串,並且每個單元格都有一個類似的大字符串。我想提取所有的名字到一個數組中。
「c1-mc-」將始終是名稱的前綴。我希望我可以使用一個函數,在該函數中我可以指定對於以「c1-mc」開頭並以vbLf(enter)結尾的每個子串,提取這些子串。 我認爲Instr()和Split()可以幫助但不知道如何繼續。
"Str: 1/2/1
End : 1/2/2
Name: cl-mc-23223322
Name: c1-mc-dddssda
Info: alot of detail
Name: c1-asa-dddssda
task: asdf
Name: c1-mc-xd132eds"
<the code which works>
For Each rng1 In table1.DataBodyRange.Columns(8).Cells
MyString = rng1.Value
Do Until InStr(MyString, "c1-mc") = 0
namestart = InStr(MyString, "c1-mc")
name = Mid(MyString, namestart)
nameend = InStr(name, vbLf) - 1
name = Left(name, nameend) 'this gives you a name
namestart = InStr(name, "c1-mc")
name = Mid(name, namestart)
nameend = InStr(name, " ") - 1
If (nameend = -1) Then
nameend = Len(name)
End If
name = Left(name, nameend) ' gives you name incase there are no next lines
MyString = Replace(MyString, name, "") 'this cuts the original string so it now starts where the name ended.
MsgBox name
i = i + 1
Loop
Next
如果你正在做大量的這個,你可能會發現尋找到正規表達式在VBA中的使用。它允許根據標準對字符串進行各種切片和切塊。這是[一個優秀的職位](http://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops)上話題。 –
您向我展示的字符串是:「Str:1/2/1End:1/2/2Name:cl-mc-23223322Name:c1-mc-dddssdaInfo:很多詳細信息名稱:c1-asa-dddssdatask:asdfName:c1 -mc-xd132eds「字符串中沒有」進入「。也許你的意思是「Str:1/2/1」&vbLF&「End:1/2/2」&vbLF&「Name:cl-mc-23223322」&vbLF ... –
@Byron感謝您的參考。 –