You can use regular expressions (AKA regex and regexp)!
While the regular expressions objects aren't enabled by default, there's a really comprehensive answer from Automate This that explains how to enable and use them at the following link:
https://stackoverflow.com/a/22542835/8213085
The function below is an example of how to use the RegExp object to replace a pattern, with a subroutine to illustrate how to use the function:
Private Function RegexReplace( _
ByVal sInput As String, _
ByVal sPattern As String, _
Optional ByVal sReplace As String = "" _
)
Dim regEx As New RegExp
With regEx
.Global = True
.IgnoreCase = False
.Pattern = sPattern
End With
If regEx.Test(sInput) Then
Let RegexReplace = regEx.Replace(sInput, sReplace)
Else
Let RegexReplace = sInput
End If
Set regEx = Nothing
End Function
Private Sub Test()
Debug.Print RegexReplace("a1b2c3", "[a-z]") ' Prints 123
Debug.Print RegexReplace("abc", "[a-z]") ' Prints an empty string
Debug.Print RegexReplace("123", "[a-z]") ' Prints 123
Debug.Print RegexReplace("abc", "a") ' Prints bc
Debug.Print RegexReplace("abc", "a", "b") ' Prints bbc
End Sub
Since the answer linked above is so comprehensive, I won't explain how to construct patterns -- but I will note that this custom function can take 3 arguments:
sInput
: The string the search
sPattern
: The regex pattern to search for
sReplace
: An optional string to replace the matched string with. Defaults to an empty string ""
The pattern [a-z]
used in the example subroutine replaces any lower-case letter between a
and z
, which is every lower case letter.
If you want to replace just the letters in qwerty
like in Gary's Student's answer, you can just supply the pattern "[qwerty]"
:
Private Sub Test()
Debug.Print RegexReplace("123456qwerty", "[qwerty]") ' Prints 123456
End Sub
Regex is really powerful -- I'd definitely recommend trying to use it. Loads of modern software is starting to support it by default. If you're struggling to figure out what pattern to use, try testing it in the following webpage:
https://regexr.com/