VBA Script To Do RegEx Search In Excel

Last Updated on April 9, 2024 by Sudhir

Sub test()
Dim eh As String
Dim allMatches As MatchCollection
Dim myMatch As Match
Dim strPattern As String
Dim regEx As RegExp
Dim rng, myCell As Range
Set regEx = New RegExp
strPattern = "SF[A-Za-z]{1,3}[-][0-9]*"
eh = ActiveSheet.Range("H3").Value
Set rng = ActiveSheet.Range("A1:AD30")
'MsgBox rng.Count

Debug.Print eh
Debug.Print "========================================="

regEx.Global = True
regEx.MultiLine = True
regEx.IgnoreCase = False
regEx.Pattern = strPattern

For Each myCell In rng
  eh = myCell.Value
  If eh <> "" Then
    Set allMatches = regEx.Execute(eh)
      
    For Each myMatch In allMatches
      Debug.Print myCell.Address & " MATCH: " & myMatch.Value
    Next myMatch
  End If
  
Next myCell

End Sub