Search code examples
excelvbastr-replace

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?


Solution

  • 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.