Pages

Tuesday, 21 December 2010

Replace all Occurrences of One String With Another

Public Function Replace(ByVal sInputVal As String, _
sFind As String, sReplaceWith As String) As String

'NOTE: IF YOU HAVE VB6 OR HIGHER,
'YOU DON'T NEED THIS. JUST USE
'THE BUILT IN REPLACE FUNCTION
Dim nPos As Long
Dim sAns As String
Dim sWkg As String

If Len(sFind) <> 0 Then
nPos = InStr(sInputVal, sFind)
If nPos <> 0 Then
sWkg = sInputVal
Do
If nPos >= Len(sWkg) Then
sAns = sAns & Left$(sWkg, Len(sWkg) - 1) _
& sReplaceWith
Else
sAns = sAns & Left$(sWkg, nPos - 1) _
& sReplaceWith
nPos = nPos + Len(sFind) - 1
End If
sWkg = Mid$(sWkg, nPos + 1)
nPos = InStr(sWkg, sFind)
Loop While nPos > 0
sAns = sAns & sWkg
Else
sAns = sInputVal
End If
Replace = sAns
Else
Replace = sInputVal
End If

End Function

No comments:

Post a Comment