Replace one character with another wherever it appears in a string

Article contributed by Bill Coan

' the following code calls the "ReplaceACharacter" function

Sub TestTheFunction()

Dim myString As String
Dim OldCharacter As String
Dim NewCharacter As String

myString = "Hello, I love you. Let me jump in your game."
OldCharacter = "e"
NewCharacter = "u"

myString = ReplaceACharacter(InWhat:=myString, FindWhat:=OldCharacter, _
ReplaceWith:=NewCharacter)

MsgBox myString

End Sub


'here's the function itself

Function ReplaceACharacter(InWhat As String, FindWhat As String, ReplaceWith As String) As String

Dim StartAtCharacter As Long

StartAtCharacter = 1

StartAtCharacter = InStr(StartAtCharacter, InWhat, FindWhat)

Do While StartAtCharacter <> 0
    InWhat = Left$(InWhat, StartAtCharacter - 1) _
            & ReplaceWith _
            & Mid$(InWhat, StartAtCharacter + 1)
    StartAtCharacter = InStr(StartAtCharacter, InWhat, FindWhat)
Loop

ReplaceACharacter = InWhat

End Functionn