Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Last active July 26, 2021 14:52
Show Gist options
  • Save JohnLBevan/833509322f3b6fe66bcbe6b5a377ab48 to your computer and use it in GitHub Desktop.
Save JohnLBevan/833509322f3b6fe66bcbe6b5a377ab48 to your computer and use it in GitHub Desktop.
VBA worksheet function implementation of a regex replace
' Simple Example Usage: `=RegexReplace(S181,"(\d+)\.(\d+)\.(\d+)", "$3-$2-$1 00:00:00")` - dd.mm.yyyy formatted date replaced with yyyy-MM-dd HH:mm:ss
' Ensure you add a reference to `Microsoft VBScript Regular Expressions 5.5` (or later)
' Thanks to AutomateThis for their answer pointing me to this library: https://stackoverflow.com/a/22542835/361842
Option Explicit
Option Base 0
Public Function RegexReplace(sourceString As String, matchPattern As String, replaceVar As String, Optional globalRegex As Boolean = True, Optional multiLine As Boolean = True, Optional ignoreCase As Boolean = True) As String
' Could improve by adding validation (e.g. is the matchPattern blank), but for now just doing a quick and dirty
Dim regEx As New RegExp
regEx.Global = globalRegex
regEx.multiLine = multiLine
regEx.ignoreCase = ignoreCase
regEx.Pattern = matchPattern
RegexReplace = regEx.replace(sourceString, replaceVar)
Set regEx = Nothing
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment