2017-04-06 76 views
-3

我有這樣一個字符串的字符串:拆分如果與RQ開始在VBA

RQ12123RQ32434RQu9798 

我需要拆分RQ的字符串。預計輸出ID:

RQ12123,RQ32434,RQu9798 

我的代碼:

WrdArray() = Split(Sheets(SdomCompareResultSheet).Cells(i, 5).Value) 
+1

你所期望的輸出到一個單元格或三個? –

+0

iam expect數組輸出,對於上面的場景,數組大小應該是3 –

+0

我的代碼WrdArray()= Split(Sheets(SdomCompareResultSheet).Cells(i,5).Value) –

回答

0

堅持你的代碼:

Dim WrdArray As Variant 

WrdArray = Split(Trim(Replace(Sheets(SdomCompareResultSheet).Cells(i, 5).Value, "RQ", " RQ"))) 

一個更通用的代碼:

Function GetArray(strng As String, id As String) As Variant 
    GetArray = Split(Trim(Replace(strng, id, " " & id))) 
End Function 

,你可以在你的 「主」 子利用如下

Sub main() 
    Dim WrdArray As Variant 
    Dim strng As String 

    strng = "RQ12123RQ32434RQu9798" 
    WrdArray = GetArray(strng, "RQ") 

End Sub 

少一些通用代碼

假設喲你知道,前兩個字母是總是通過解析字符串ID:

Function GetArray(strng As String) As Variant 
    GetArray = Split(Trim(Replace(strng, Left(strng, 2), " " & Left(strng, 2)))) 
End Function 

被利用類似如下:

Sub main() 
    Dim WrdArray As Variant 
    Dim strng As String 

    strng = "RQ12123RQ32434RQu9798" 
    WrdArray = GetArray(strng) 

End Sub 
+0

這是一個通用的解決方案,或僅用於這個數據,iam期待一個通用的解決方案 –

+0

這是一個適用於您在問題中顯示的代碼的通用解決方案。只要用's'替換'Sheets(SdomCompareResultSheet).Cells(i,5).Value''''''s'是你想要處理的字符串 – user3598756

2

考慮:

Sub dural() 
    Dim s As String, t As String 

    s = "RQ12123RQ32434RQu9798" 
    t = Mid(Replace(s, "RQ", ",RQ"), 2) 
    MsgBox t 
End Sub 

enter image description here

編輯#1:

在輸入字符串「RQ」的每一次出現將得到昏迷預置到它(除了第一個「RQ」)

EDIT#2:

爲了將結果存儲在一個陣列:

Sub dural() 
    Dim s As String, t As String 

    s = "RQ12123RQ32434RQu9798" 
    t = Mid(Replace(s, "RQ", ",RQ"), 2) 
    MsgBox t 

    ary = Split(t, ",") 
End Sub 
+0

如果有多個ID以RQ開頭,此代碼是否可以工作? –

+0

我需要將結果存儲在數組中 –

+0

@PrakashSingh請參閱我的**編輯#2 ** –