如何用大写字母或美元('$')符号分割字符串

时间:2019-06-14 18:33:13

标签: vba

我在一个单元格中显示了这个字符串,上面写着“没有罚款$ 400”

我想将字符串拆分为:str1 =“ No惩罚”; str2 =“无罚”; str3 =“ $ 400”

我想到了用大写字母和$符号分割字符串,但是我不确定如何。

    stri = "No penalty No penalty $400"
    temp = ""
    temp = stri
    For i = 1 To Len(temp)
        If Mid(temp, i, 1) = UCase(Mid(temp, i, 1)) Then
            If i <> 1 Then
                str1 = Left(temp, i - 1) + Right(temp, Len(temp) - i + 1)
                i = i + 1
            End If
        End If
    Next i
    splitbycaps = temp

我现在很迷路。

1 个答案:

答案 0 :(得分:2)

Option Explicit

Sub Test()

    Dim s As String
    Dim ocMatches As Object
    Dim i As Long
    Dim a() As String

    s = "No penalty No penalty $400"
    With CreateObject("VBScript.RegExp")
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = "[A-Z$][^A-Z$]*"
        Set ocMatches = .Execute(s)
    End With
    If ocMatches.Count > 0 Then
        ReDim a(1 To ocMatches.Count)
        For i = 1 To UBound(a)
            a(i) = Trim(ocMatches(i - 1).Value)
        Next
    End If

End Sub