Skip to content

Instantly share code, notes, and snippets.

@neblish
Created September 20, 2017 10:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save neblish/b328bc373669d13bec5b3f04ec02d2a3 to your computer and use it in GitHub Desktop.
Save neblish/b328bc373669d13bec5b3f04ec02d2a3 to your computer and use it in GitHub Desktop.
MS Excel - VBA function to extract text using Regex
' Shamelessly leeched from StackOverflow: https://stackoverflow.com/questions/7086270/how-to-extract-text-within-a-string-of-text
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional separator As String = ", ") As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
Dim i As Long, j As Long
Dim result As String
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & (separator & allMatches.Item(i).submatches.Item(j))
Next
Next
If Len(result) <> 0 Then
result = Right$(result, Len(result) - Len(separator))
End If
RegexExtract = result
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment