Function searchReplace(startString As String, searchString As String, replaceString As String) As String
%REM
Function searchReplace
Charles F. Phillips
23 May 2001
This function does a simple text search and replace,
no matter how many occurances of the search string.
The beauty of this one is that it's backwards compatible
with R4 and you CAN include the search string as part
of the replacement string without worry of ending up in
an endless loop!
i.e., you can replace "&" with "&" and not go into a loop
%END REM
'just in case a non-string value was passed
On Error Resume Next
'dim strings used to reassemble final product
Dim sPart1 As String
Dim sPart2 As String
'dim iPos for use with Instr
Dim iPos As Integer
'dump incoming string into searchReplace in order to
'fulfill function's output even if searchstring isn't found
searchReplace = startString
'if startStrng or searchString were empty, then exit
If searchReplace ="" Or searchString ="" Then Exit Function
'Use Instr to determine if startString actually contains searchstring.
'We will care where it actually is located, but it's also a quick "Contains" type of check.
iPos = Instr(searchReplace, searchString)
'If Contains, then iPos will be a value higher than zero and the Do loop executes,
'but if not contains, then a zero is returned and we never enter Do loop.
Do Until iPos = 0
'Get everything to the left of the startstring
'iPos minus 1 will be all characters to the left of, but not including, searchstring
sPart1 = Left$(searchReplace, iPos-1)
'Get number of characters to the right of the searchstring:
'Total length of the string minus ((iPos-1) plus length of searchstring)
sPart2 = Right$(searchReplace, Len(searchReplace)-((iPos-1)+Len(searchString)))
'Reassemble searchReplace with parts 1 and 2 surrounding the replacement value
searchReplace = sPart1 & replaceString & sPart2
'Check to see if there is another occurance of the searchString,
'and if so, keep the loop going until no more occurances are found.
'Start looking after the last occurrance, plus the length of the replaceString
'in order to prevent something like search for "&" and replace with "&" from going into an infinite loop
iPos = Instr((iPos-1)+Len(replaceString), searchReplace, searchString)
Loop
End Function