【问题标题】:VBA - Find certain strings in a worksheetVBA - 在工作表中查找某些字符串
【发布时间】:2015-01-15 18:16:22
【问题描述】:

我想创建一个可以在包含以下内容的 Excel 工作表中查找单元格的宏或 UDF: POxxx 邮政信箱 xxxxxxx 采购订单#xxxxx 采购订单#xxxx (其中 x 是数字) 字符串可以在单元格的开头或中间。 此外,函数/宏不应找到包含诸如 CORPORATE 之类的条目的单元格,其中 PO 是单词的一部分。

所有包含合格数据的单元格都应突出显示。

【问题讨论】:

  • 是什么阻止你这样做?
  • 蒂姆,我很难找到一种可以在单元格内容中的任何位置找到子字符串的语法,尤其是在单元格的开头。
  • @TimWilliams,我在寻找可以在单元格内容中的任何位置找到子字符串的语法时遇到问题。如果子字符串位于单元格的开头,我似乎没有找到可以找到子字符串的语法。 Gary 的学生提供的 UDF 似乎也是这种情况。

标签: string excel extract excel-udf vba


【解决方案1】:

这个小UDF会返回1是否匹配存在,否则0

Public Function IsItThere(r As Range) As Long
    Dim st As String
    st = "0,1,2,3,4,5,6,7,8,9"
    ary = Split(st, ",")
    st = r.Text
    IsItThere = 1
    For Each a In ary
    If InStr(1, st, "PO" & a) > 1 Then Exit Function
    If InStr(1, st, "PO " & a) > 1 Then Exit Function
    If InStr(1, st, "PO#" & a) > 1 Then Exit Function
    If InStr(1, st, "PO# " & a) > 1 Then Exit Function
    Next a
    IsItThere = 0
End Function

您也可以使用正则表达式来查找模式。

【讨论】:

  • 感谢您的回复。蒂姆,为了回答你的问题,当子字符串位于单元格的开头时,我很难找到正确的语法来查找子字符串。它似乎也有同样的问题
【解决方案2】:

试试这个:

Sub Tester()
    Dim c As Range
    For Each c In Selection.Cells
        c.Interior.Color = IIf(RegexpTest(c.Value), vbRed, vbGreen)
    Next c
End Sub


Function RegexpTest(v As String)
    Static re As Object 'note static: you must reset the VB environment
                        '  (press the "stop" button) if you edit the
                        '   Pattern below
    If re Is Nothing Then
        Set re = CreateObject("VBScript.RegExp")
        '"PO" then optional #, optional space, then 2-5 digits
        re.Pattern = "PO#?\s?\d{2,5}"
        re.ignorecase = True
    End If
    RegexpTest = re.test(v)
End Function

【讨论】:

  • 蒂姆,太好了。这就是我要找的。也感谢您对语法的澄清。
  • Tim,对不起,如何添加可选空格#? (捕获 PO #555 或 PO #7888)
  • 试试PO\s?#?\s?\d{2,5}
猜你喜欢
  • 2020-05-16
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-25
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
相关资源
最近更新 更多