Replace multiple characters in a string variable (VBA)

雨燕双飞 提交于 2019-12-05 10:26:31

You could use an array and loop over its elements:

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

Each element of junk can be either a sub-string or a single character.

Does it need to be VBA? This formula should also work:

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

The output wil be 'rplc'

I found this post quite helpful so I thought I would share how I was able to use it to my advantage. Combining the accepted answer from "Gary's Student" with this comment by Charles Williams, I came up with a slick way to remove non numeric characters from any given string.

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

I hope this helps someone. Cheers!

If it is only about a few characters then I would go with Marco but in VBA:

unitNr = Replace(Replace(unitNr, "OE", ""), ";", "")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!