【问题标题】:How to extract a generic string (pattern) of character & digits in VBA?如何在 VBA 中提取字符和数字的通用字符串(模式)?
【发布时间】:2017-06-20 07:58:12
【问题描述】:

我正在尝试构建一个长期以来一直被阻止的函数。

我想从单元格中的字符串中提取一个子字符串,例如“ABC123”或“AB1234”。有一些条件:

  • 它必须像“ABC123”或“AB1234”,所以3 char and 3 Numeric2 char and 4 Numeric。 IE。 “CDE789”因此也是模式之一。
  • 我们正在查看的字符串没有特定的大小。它可能包含或不包含模式。
  • 如果搜索词的前后应该有一个空格(那么只有那个模式)。并不是说如果我们位于字符串的开头或结尾,它就不适用。
  • 该函数应返回该特定字符串集(即在除已存在的列之外的列中)。

我尝试了类似的函数、数组甚至字典,但我找不到解决方案。例如,我尝试通过字符串的 LEN 循环,细分为 6 个变量,并使用 IF 检查前 2 个在哪里是字符,最后一个是在哪里是数字。它相当繁重,不适用于大量数据。

另外请原谅我的英语不好,不要犹豫,纠正我,我也是她学习这个:)

谢谢!

【问题讨论】:

  • 看看正则表达式。
  • 正则表达式?我对此并不熟悉,但这是一个绝妙的主意!谢谢!
  • like "[A-Z]" 做事的方式,但我认为你会迷失在这样的组合中,正则表达式对你来说看起来更干净。

标签: excel vba wildcard


【解决方案1】:

VBA:用函数计算字母和数字的数量

Function AlphaNumeric(pInput As String) As String
'Updateby20140303
Dim xRegex As Object
Dim xMc As Object
Dim xM As Object
Dim xOut As String
Set xRegex = CreateObject("vbscript.regexp")
xRegex.Global = True
xRegex.ignorecase = True
xRegex.Pattern = "[^\w]"
AlphaNumeric = ""
If Not xRegex.test(pInput) Then
    xRegex.Pattern = "(\d+|[a-z]+)"
    Set xMc = xRegex.Execute(pInput)
    For Each xM In xMc
        xOut = xOut & (xM.Length & IIf(IsNumeric(xM), "N", "L"))
    Next
    AlphaNumeric = xOut
End If
End Function

【讨论】:

  • 如果我在单元格中尝试,它只会给我空白单元格。
  • 你应该把这段代码放在Module中。并在 A3 列中输入如下内容并将您的值 A2 列 =AlphaNumeric(A2)
【解决方案2】:

编辑:找到!

感谢您的回答,我做到了:

Function GetID(MyRange As Variant)

    Dim regEx As Object
    Set regEx = CreateObject("vbscript.regexp")
    Dim strPattern As String
    Dim strInput As String
    Dim strReplace As String
    Dim strOutput As Object

    strPattern = "([a-zA-Z]{3})([0-9]{3})"

    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    If strPattern <> "" Then
        strInput = MyRange.Value
        strReplace = strPattern

        If regEx.test(strInput) Then
            Set strOutput = regEx.Execute(MyRange.Value)
            GetID = regEx.Execute(strInput)(0)
        Else
            GetID = "Not matched"
        End If
    End If

End Function

它有效。但是,有一种情况不是: - 如果我的性格比我的模式更多。例如 ABC123456 将返回 ABC123。不应该考虑,只有“ABC123”。甚至 AABC123 也被考虑在内,但它不应该被考虑在内。

编辑:它通过在开头和结尾添加 \b 来工作:

"\b([a-zA-Z]{3})([0-9]{3})\b"

非常感谢!

【讨论】:

    【解决方案3】:

    你应该使用正则表达式。

    这里有一个根据需要返回匹配项的示例: Returning a regex match in VBA (excel)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      • 2021-12-11
      • 2017-07-19
      相关资源
      最近更新 更多