替换字符串变量中的多个字符 (VBA)

Replace multiple characters in a string variable (VBA)

如何替换字符串变量中的多个内容?

这里是我在 VBA 中的示例函数:

Private Function ExampleFunc(ByVal unitNr$) As String
    If InStr(unitNr, "OE") > 0 Then
        unitNr = Replace(unitNr, "OE", "")
        unitNr = Replace(unitNr, ";", "")
    End If
...
End Function

有更好的解决方案吗?

是否需要VBA?这个公式也应该有效:

=SUBSTITUTE(SUBSTITUTE("replace","e",""),"a","")

输出将是'rplc'

您可以使用数组并循环其元素:

Sub MAIN()
    Dim s As String

    s = "123456qwerty"
    junk = Array("q", "w", "e", "r", "t", "y")

    For Each a In junk
        s = Replace(s, a, "")
    Next a

    MsgBox s
End Sub

垃圾的每个元素可以是子字符串或单个字符。

我发现这个 post 非常有用,所以我想我会分享我是如何利用它来发挥我的优势的。结合 "Gary's Student" 和 this comment by Charles Williams 接受的答案,我想出了一个巧妙的方法来从任何给定的字符串中删除非数字字符。

Public Function RemoveNonNumChars(s As String) As String
    Dim bytes() As Byte
    Dim char As String

    bytes = StrConv(s, vbFromUnicode)
        For Each c In bytes
            char = chr(c)
            If Not IsNumeric(char) Then
                'remove character from array
                s = Replace(s, char, "")
                Debug.Print "Removing " & char & " from string." & Chr(13) s
            End If
        Next c
End Function

我希望这对某人有所帮助。干杯!

如果只有几个字符那么我会选择 Marco 但在 VBA:

unitNr = Replace(Replace(unitNr, "OE", ""), ";", "")

您可以使用正则表达式(又名 regexregexp)!

虽然默认情况下不启用正则表达式对象,但 Automate This 提供了一个非常全面的答案,解释了如何启用和使用它们 link:


下面的函数是如何使用 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

由于上面 link 的回答非常全面,我不会解释如何构造模式 -- 但我会注意到这个自定义函数可以接受 3 个参数:

  • sInput: 搜索的字符串
  • sPattern:要搜索的正则表达式模式
  • sReplace:用于替换匹配字符串的可选字符串。默认为空字符串 ""

示例子例程中使用的模式 [a-z] 替换 az 之间的任何小写字母,即每个小写字母。

如果您只想像 中那样替换 qwerty 中的字母,您可以只提供模式 "[qwerty]":

Private Sub Test()
    Debug.Print RegexReplace("123456qwerty", "[qwerty]")  ' Prints 123456
End Sub

正则表达式真的很强大——我绝对推荐尝试使用它。默认情况下,大量现代软件开始支持它。如果您正在努力找出要使用的模式,请尝试在以下网页中进行测试:

https://regexr.com/