Implement Search And Replace All

Search for all the appearances of specific substring within other string, and replace them all with new substring.

Form Code

Public Function ReplaceAll(searchstring As String, _
  findstring As String, replacestring As String) As String
   Dim curpos As Long
   curpos = 1
   Do
      curpos = InStr(curpos, searchstring, findstring)
      searchstring = Left$(searchstring, curpos - 1) & _
      replacestring & Right$(searchstring, Len(searchstring) _
      - curpos - Len(findstring) + 1)
   Loop Until InStr(searchstring, findstring) = 0
   ReplaceAll = searchstring
End Function
 

Private Sub Form_Load()
'the example below replace all the "go" substrings with "bad",
'in the string "good boy go home"

    MsgBox ReplaceAll("good boy go home", "go", "bad")
End Sub

Go Back