【问题标题】:How to split a string when an alphanumeric word found in a string using vba?使用vba在字符串中找到字母数字单词时如何拆分字符串?
【发布时间】:2019-05-04 17:51:22
【问题描述】:

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

现在,我想将字符串分成两部分字符串在单元格 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

【问题讨论】:

  • 你还没有告诉 use 代码有什么问题以及错误在哪一行抛出
  • 这段代码没有错。我只想将上述条件添加到我的代码中。
  • @pz1 实际上您是要求我们将上述条件添加到您的代码中吗?那不是免费的编码服务。您应该尝试自己添加它们,然后显示您尝试过的内容以及您的问题或错误在哪里。
  • @Pᴇʜ 好的,我会在这里添加。

标签: excel vba


【解决方案1】:

没有正则表达式

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

【讨论】:

  • 非常感谢您的帮助。然而,这段代码并没有给我预期的输出。例如,我有字符串“prd 的长度为 90x90mm 长”。运行上述代码后,b1 单元格包含单词“length”,c1 具有“of prd is 90x90mm long”。我想在 b1 中有字符串“prd 的长度是”,在 C1 中有文本“90x90mm 长”。如果 a1 中的字符串像“90x90mm 长”。它不应该拆分字符串,因为字符串的第一个单词是字母数字。它应该将其粘贴到 b1 中。
猜你喜欢
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 2014-12-22
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 2013-03-12
  • 2018-09-07
相关资源
最近更新 更多