Skip to content

Instantly share code, notes, and snippets.

@zloydadka
Created October 16, 2011 16:31
Show Gist options
  • Save zloydadka/1291113 to your computer and use it in GitHub Desktop.
Save zloydadka/1291113 to your computer and use it in GitHub Desktop.
RegExp in VBA example 2
Option Explicit
#Const LateBind = True
Function RegExpSubstitute(ReplaceIn, _
ReplaceWhat As String, ReplaceWith As String)
#If Not LateBind Then
Dim RE As RegExp
Set RE = New RegExp
#Else
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
#End If
RE.Pattern = ReplaceWhat
RE.Global = True
RegExpSubstitute = RE.Replace(ReplaceIn, ReplaceWith)
End Function
Function RegExpFind(FindIn, FindWhat As String, _
Optional IgnoreCase As Boolean = False)
Dim i As Long
#If Not LateBind Then
Dim RE As RegExp, allMatches As MatchCollection, aMatch As Match
Set RE = New RegExp
#Else
Dim RE As Object, allMatches As Object, aMatch As Object
Set RE = CreateObject("vbscript.regexp")
#End If
RE.Pattern = FindWhat
RE.IgnoreCase = IgnoreCase
RE.Global = True
Set allMatches = RE.Execute(FindIn)
ReDim rslt(0 To allMatches.Count - 1)
For i = 0 To allMatches.Count - 1
rslt(i) = allMatches(i).Value
Next i
RegExpFind = rslt
End Function
RegExpSubstitute(A26,"Jim","Pat")
RegExpSubstitute(A22,"(\S+)(\s+)(\S+)","$3,$2$1")
RegExpFind(A29,"cat|dog")
RegExpFind(F15,"\d*")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment