如果在VBA中以RQ开头,则拆分字符串

时间:2017-04-06 14:55:46

标签: excel vba excel-vba

我有一个字符串:

RQ12123RQ32434RQu9798 

我需要通过RQ分割字符串。预期输出ID:

RQ12123,RQ32434,RQu9798

我的代码:

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

2 个答案:

答案 0 :(得分: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"除外)

修改#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

答案 1 :(得分: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

你可以在你的" main"子如下

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