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

时间:2016-05-02 13:23:06

标签: excel vba excel-vba str-replace

如何在字符串变量中替换多个东西?

这是我在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

有更好的解决方案吗?

4 个答案:

答案 0 :(得分:7)

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

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

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

答案 1 :(得分:0)

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

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

输出将是'rplc'

答案 2 :(得分:0)

我发现这篇文章非常有用,所以我想我会分享我是如何利用它来发挥我的优势的。结合来自"加里的学生"通过this comment 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

我希望这有助于某人。干杯!

答案 3 :(得分:0)

如果它只有几个字符,那么我会选择Marco而不是VBA:

unitNr = Replace(Replace(unitNr, "OE", ""), ";", "")
相关问题