Replace multiple characters in a string variable (VBA)

yuro picture yuro · May 2, 2016 · Viewed 38.2k times · Source

How can I replace more than one thing in a string variable?

Here my example function in 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

Is there a better solution?

Answer

Gary's Student picture Gary's Student · May 2, 2016

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.