I’ve found many things online that show me how to create the function and how to implement it, but nothing is helping me figure out why it won’t accept the function’s name.
I opened the Visual Basic section under developer. I’ve entered my code and I assume that is it? Ctrl + S only makes me save the sheet, not the code.
The purpose of my code is to take a string and remove the first 7 characters, one of which will be a ; and the following 6 will be random numbers. I have some more fixing to do, such as removing 4 random characters from the end, but I wanted to test it out first.
Here is my code:
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]{6}"
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
I’m not sure if there is a step that I am missing that will allow excel to accept my code.
Thanks for any help!
Check out this thread. You most likely missed to add a reference to Microsoft VBScript Regular Expressions 5.5
. You find it under “How to use”:
How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops
Answer:
I have recut the code below to clean up the variables and use late binding
Also your current code doesnt test for the user taking more than one cell into the range.
Function simpleCellRegex(Myrange As Range) As String
Dim regEx As Object
Dim strPattern As String
Dim strReplace As String
Set regEx = CreateObject("vbscript,regexp")
strPattern = "^[;][0-9]{6}"
If Len(strPattern) = 0 Then Exit Sub
simpleCellRegex = "Not matched"
strReplace = vbNullString
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
If .test(Myrange) Then simpleCellRegex = .Replace(Myrange.Value2, strReplace)
End With
End Function
Tags: regexregex