使用vba在字符串中找到字母数字单词时如何拆分字符串?

时间:2019-05-03 00:03:56

标签: excel vba

我有下面的代码,该代码在字符串中找到字母数字单词,然后将其更改为大写。

现在,我想将字符串分成两部分。字符串位于单元格A1中。单元格值为“免费90x90mm露水”

如果字符串的第一个单词是字母数字,则不要执行任何操作。将值粘贴到单元格B1中。

如果字符串包含字母数字单词,则将字符串分成两列。

单元格B1应包含从开始到字母数字单词的单词。即“免费”

单元格C1包含从字母数字单词到字符串结尾的单词。即“ 90x90mm露水”

Sub Main()
    Dim longString, result As String
    Dim arrayString() As String
    Dim newarr As String
    Dim substr As String

    Set objRegExp_1 = CreateObject("vbscript.regexp")

    objRegExp_1.Pattern = "((?:[a-z][a-z]*[0-9]+[a-z0-9]*))" 'REGEX for alphanumeric words in the string

    longString = "Free 90x90mm desc"

    arrayString = Split(longString) 'Splits the string into an array of words so that each one can be matched with the REGEX pattern to check if its alphanumeric

    For i = 0 To UBound(arrayString)
        Set regExp_Matches = objRegExp_1.Execute(arrayString(i))

        If regExp_Matches.Count = 1 Then
            arrayString(i) = UCase(arrayString(i)) 'If a pattern match is found, the corresponding string is converted to uppercase and stored back
        End If
    Next

    result = Join(arrayString, " ") 'Combines elements of the modified array of words into a single string
    MsgBox (result)
End Sub

1 个答案:

答案 0 :(得分:0)

没有正则表达式

Sub Main()
    Dim arrayString() As String
    longString = Range("A1").Text
    arrayString = Split(longString) 'Splits the string into an array of words so that each one can be matched with the REGEX pattern to check if its alphanumeric
    s = ""
    For i = 0 To UBound(arrayString)
      If alfaNumeric(arrayString(i)) = True Then
        p = InStr(longString, arrayString(i))
        Exit For
      Else
        s = s & arrayString(i) & " "
      End If
    Next
    If s = "" Then
      Range("B1") = longString
    Else
      Range("B1") = s
      Range("C1") = Right(longString, Len(longString) - p + 1)
    End If
End Sub