【问题标题】:VBA check if a string follows pattern, space, two letters, six digitsVBA 检查字符串是否遵循模式、空格、两个字母、六个数字
【发布时间】:2016-08-22 20:12:19
【问题描述】:

我需要检查单元格中的最后 9 个字符是否遵循模式。 搜索的模式是空格两个字母和六个数字。 单元格包含一些文本,则应具有此模式。 通常搜索到的单元格内容如下所示: "拖拉机割草机 PT009988" 问候 米哈乌

【问题讨论】:

  • 查找“在 vba 中使用正则表达式”,如果您仍然无法自行解决问题,请返回并展示您的尝试,我们会为您提供帮助。
  • 我猜你需要正确的功能:D
  • 谢谢你,我想我会设法解决的。

标签: vba excel


【解决方案1】:

这将对此进行测试。

Public Function RegExTest(sCellContent As String) As String
Dim sContent As String, sMatch As Variant, i As Long

sContent = Right(sCellContent, 9)

With CreateObject("VBScript.RegExp")
    .Global = True
    .ignorecase = True
    .Pattern = " [A-Za-z]{2}[0-9]{6}"
    If .test(sContent) Then
        Set sMatch = .Execute(sContent)
        RegExTest = sMatch(i)
        Exit Function
    End If
End With
End Function

这是需要匹配的模式:
" [A-Za-z]{2}[0-9]{6}"

1 个空格,2 个字母(大写和小写)和 6 个数字。

如果A1 范围内的值是Tractor mowers PT009988,并且您将此公式放入B1 =RegExTest(A1),那么B1 中的输出将为PT009988

如果您不在乎这是否在最后 9 个字符中,请将 sContent = Right(sCellContent, 9) 更改为 sContent = sCellContent

【讨论】:

    【解决方案2】:

    试试这个(如果你想包含大小写字符)

    Dim c
    For Each c In Selection
        If c.Value Like "* [A-Z,a-z][A-Z,a-z]######" Then _
            Debug.Print c.Value
    Next c
    

    https://msdn.microsoft.com/en-us/library/swf8kaxw.aspx

    【讨论】:

      猜你喜欢
      • 2016-06-07
      • 2014-08-03
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 2015-08-22
      • 2022-01-17
      • 1970-01-01
      相关资源
      最近更新 更多