2015-06-19 69 views
2

我想知道是否有辦法通過指定開始的幾個字符和結束字符來提取子字符串的字符串。通過指定子字符串的第一個和最後一個字符串來提取字符串中的子字符串

作爲一個例子,我在工作簿中的單元格中有類似於問題底部的字符串,並且每個單元格都有一個類似的大字符串。我想提取所有的名字到一個數組中。

「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 
+1

如果你正在做大量的這個,你可能會發現尋找到正規表達式在VBA中的使用。它允許根據標準對字符串進行各種切片和切塊。這是[一個優秀的職位](http://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops)上話題。 –

+0

您向我展示的字符串是:「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 ... –

+0

@Byron感謝您的參考。 –

回答

0

重新閱讀您的問題後編輯我想我沒有正確回答它。請詳細說明每個單元格中實際包含的內容以及我們正在討論的單元格數量(1?)。

字符串是字符的串聯。在幾行寫你的字符串並不意味着它實際上改變了。正如你所說的,當你輸入chr(10)或者vbLF時,行改變就會發生。我不確定你發佈的字符串中哪部分想要提取。假設你想利用一個單元的名稱,以及該字符串是在字符串變量[MyString中]舉行:

Dim name as string 
Dim namestart as integer 
Dim nameend as integer 

namestart = Instr(Mystring, "c1-mc-") 
name = Mid(Mystring, namestart + 1) 
nameend = Instr(Mystring, vbLF) 
name = Left(name, nameend) 

現在的名稱將包含您的字符串的名稱。測試一下(我沒有,你可能需要調整一些小的東西),當你有它時,使用for循環遍歷你的單元格,並將名稱添加到你想要的數組。

編輯2: 既然你要提取的名稱的所有實例在你的,我會把它改成這樣:

Dim name as string 
Dim namestart as integer 
Dim nameend as integer 
Dim namearray() as string 
Dim i as integer 

Do Until Instr(Mystring, "c1-mc-") = 0 'will continue filling the array until Mystrign no longer has any names) 
    namestart = Instr(Mystring, "c1-mc-") 
    name = Mid(Mystring, namestart + 1) 
    nameend = Instr(Mystring, vbLF) 
    name = Left(name, nameend) 'this gives you a name 
    Mystring = Mid(Mystring, Instr(Mystring, name)) 'this cuts the original string so it now starts where the name ended. 
    namearray(i) = name 
    i = i + 1 
Loop 
+0

我在我的問題中發佈的字符串是描述事件的列的單元格值。可以有大約4000-5000行具有相同的字段。 在我的問題中,您可以看到名稱I.E「c1-mc-23223322」等4個實例。我想要在數組中提取所有名稱。 您上面發佈的代碼,我如何使用它在單元格值上運行多次? – Tan12

+0

@Byron謝謝你,我也會看看正則表達式 – Tan12

+0

我的編輯能幫助你嗎?現在它應該取得單元格中的所有名稱(我還沒有對它進行測試,所以有一個可能性就是要將+1添加到字符位置,例如,使用debug.print來確定添加的內容什麼是剪切。) –

相關問題