您可以使用正则表达式(AKA regex 和 regexp)!
虽然默认情况下不启用正则表达式对象,但 Automate This 提供了一个非常全面的答案,解释了如何在以下链接中启用和使用它们:
https://stackoverflow.com/a/22542835/8213085
下面的函数是一个如何使用RegExp对象替换模式的例子,用一个子程序来说明如何使用该函数:
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
由于上面链接的答案非常全面,我不会解释如何构造模式——但我会注意这个自定义函数可以接受 3 个参数:
-
sInput: 搜索的字符串
-
sPattern:要搜索的正则表达式模式
-
sReplace:替换匹配字符串的可选字符串。默认为空字符串""
示例子例程中使用的模式[a-z] 替换了a 和z 之间的任何小写字母,即每个小写字母。
如果您只想替换 qwerty 中的字母,就像在 Gary's Student's answer 中一样,您可以提供模式 "[qwerty]":
Private Sub Test()
Debug.Print RegexReplace("123456qwerty", "[qwerty]") ' Prints 123456
End Sub
Regex 真的很强大——我绝对推荐尝试使用它。默认情况下,大量现代软件开始支持它。如果您不知道要使用哪种模式,请尝试在以下网页中进行测试:
https://regexr.com/