繁体   English   中英

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

[英]How to split a string when an alphanumeric word found in a string using vba?

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

现在,我想将字符串分成两部分。字符串在单元格A1中。 电池值为“Free 90x90mm dewsc”

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

如果string包含字母数字字,则将字符串拆分为两列。

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

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

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

没有正则表达式

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM