I found the following StackOverflow question.
How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops
I added "Microsoft VBScript Regular Expressions 5.5" to my references in the VBA interface, and typed in 12abc
in cell A1
as in the example. I then did Insert -> Module and copied the following code to the code box:
Function simpleCellRegex(Myrange As Range) As String
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim strOutput As String
strPattern = "^[0-9]{1,3}"
If strPattern <> "" Then
strInput = Myrange.Value
strReplace = ""
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.test(strInput) Then
simpleCellRegex = regEx.Replace(strInput, strReplace)
Else
simpleCellRegex = "Not matched"
End If
End If
End Function
When I type =simpleCellRegex(A1)
in cell B1
I get the error
Compile error: method or data member not found
In the debugger the first line of the code is highlighted.
Someone in a comment to an answer mentioned that an error might occur if the code is in ThisWorkbook
, but mine is in Modules
.