Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple characters in a string variable (VBA)

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?

like image 923
yuro Avatar asked May 02 '16 13:05

yuro


1 Answers

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.

like image 104
Gary's Student Avatar answered Nov 15 '22 09:11

Gary's Student