在正则expression式函数中Excel 2010 VBA“无效的过程调用或参数”错误

我正在使用Excel 2010中的以下RegEx函数,并且在函数的最后一行出现“Invalid Procedure Call or Argument”错误。 我用ActiveCell.Value取代常量(注释掉)。 常数确实工作正常,虽然单元格值没有。
什么导致这个错误发生?
我感谢在这方面的任何帮助。 谢谢。

Sub SUB1() Dim c As Variant For Each c In Worksheets("Sheet1").Range("A1:D10").Cells 'MsgBox (c) If RE6(c.Value) Then c.Interior.ColorIndex = 7 Else c.Interior.ColorIndex = 6 End If Next End Sub Sub Test() 'Const strTest As String = "qwerty123456uiops" Dim strTest As String strTest = ActiveCell.Value MsgBox RE6(strTest) End Sub Function RE6(strData As String) As String Dim RE As Object Dim REMatches As Object Set RE = CreateObject("vbscript.regexp") With RE .MultiLine = False .Global = False .IgnoreCase = True .Pattern = "[0-9][0-9][0-9][0-9][0-9][0-9]" End With Set REMatches = RE.Execute(strData) MsgBox ("REMatches.Count" & REMatches.Count) 'If Not REMatches Is Nothing Then If REMatches.Count <= 0 Then RE6 = "" Else RE6 = REMatches(0) End If 'Else 'End If End Function 

您的代码似乎旨在testing在Sheet1 A1:D10中的每个单元格中是否出现连续的6位数字编号,即您正在查找Boolean真/假

  1. 使用更简单的模式Re.Pattern = "[0-9]{6}"
  2. 使用正则Regexptesting方法 – 您不需要收集匹配,只是为了知道是否存在(如Re.Global = False
  3. 从你的函数返回一个Boolean结果

     Function RE6(strData As String) As Boolean Dim RE As Object Set RE = CreateObject("vbscript.regexp") With RE .MultiLine = False .Global = False .IgnoreCase = True .Pattern = "[0-9]{6}" RE6 = .Test(strData) End With End Function 

最有可能没有匹配:如果您testing.Count属性是零?

你的函数应该testing,并返回一个合适的值(空string也许)。

编辑:如果你只想检查模式的存在或不存在,那么使用.Test()比使用.Execute()更容易。 我改变你的函数返回一个布尔值,在这种情况下更自然。

 Sub CheckCellValues() Dim c As Range For Each c In Worksheets("Sheet1").Range("A1:D10").Cells If RE6(c.Value) Then c.Interior.ColorIndex = 7 Else c.Interior.ColorIndex = 6 End If Next End Sub Function RE6(strData As String) As Boolean Dim RE As Object Dim REMatches As Object Set RE = CreateObject("vbscript.regexp") With RE .MultiLine = False .Global = False .IgnoreCase = True .Pattern = "[0-9][0-9][0-9][0-9][0-9][0-9]" End With RE6 = RE.Test(strData) 'much simpler... 'or... 'REMatches = RE.Execute(strData) 'RE6 = (REMatches.Count > 0) End Function