如何从Visual Basic,Excel中的函数返回matchCollection

时间:2017-03-15 12:19:54

标签: regex excel vba

我试图从函数返回matchCollection,以便能够遍历我的匹配并将它们写入函数外的excel单元格。

我得到运行时错误91:对象变量或With block变量未设置,当我的代码出现时:

如果matches1.Count<> 0然后

这是我的代码:

Sub simpleRegex()

  Dim ShortRange As range
  Set ShortRange = ActiveSheet.range("A2:A505")
  Dim strInput1 As String
  Dim matches1 As MatchCollection

  For Each cell In ShortRange

    strInput1 = cell.Value

    Set matches1 = CheckMatch(strInput1)

    If matches1.Count <> 0 Then
        cell(1, 3).Value = matches1(0).SubMatches(2)
        cell(1, 4).Value = matches1(0).SubMatches(3)
    End If

  Next

End Sub

Public Function CheckMatch(str As String) As MatchCollection

  Dim strPattern1 As String
  Dim strInput As String

  Dim regEx As New RegExp
  Dim matches As MatchCollection
  Dim Match As Boolean

  Match = False


  strPattern1 = "((storlek|strl|stl|strlk|storleken|storl|size|storleksmärkt|storl|storlk|st).{0,2}?(?:[^\s]+)?.{0,2}?)?(30|32|34|36|38|40|42|44|46|48|50).?(30|32|34|36|38|40|42|44|46|48|50)?"

   strInput = str

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

   If regEx.test(strInput) Then
     Match = True
     Set matches = regEx.Execute(strInput)
   End If

   Set CheckMatch = matches

End Function

有谁知道如何解决这个问题?

0 个答案:

没有答案