title: How to return a matchCollection from function in Visual Basic, Excel
body: <p>I'm trying to return a matchCollection from a function to be able to loop through my matches and write them to excel cells outside the function. </p>
  
  <p>I get the run-time error 91: Object variable or With block variable not set, when my code comes to:</p>
  
  <p>If matches1.Count &lt;> 0 Then</p>
  
  <p>This is my code:</p>
  
  <pre><code>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 &lt;&gt; 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
  </code></pre>
  
  <p>Anyone who knows how this can be fixed? </p>