Function to Replace Substring within a String:   Return to List

' with NumberToReplace as Optional Last Parameter

Public Function ReplaceWithin(ByVal strString As String, _
            ByVal strFind As String, _
            ByVal strReplace As String, _
            Optional ByVal NumberToReplace As Integer) As String

' Purpose: To replace all occurrences of one string in another
Dim intPos As Integer
Dim intLP As Integer
Dim intLen As Integer
Dim strTemp As String
Dim intCount As Integer
intCount = 0

' find each search string and replace with target
intLen = Len(strFind)
intPos = InStr(strString, strFind)
While intPos <> 0
    If NumberToReplace > 0 And NumberToReplace = intCount Then
        GoTo LOOP_ESCAPE
    End If
    strTemp = strTemp & Left$(strString, intPos - 1)
    strTemp = strTemp & strReplace
    strString = Right$(strString, Len(strString) - intPos - intLen + 1)
    intPos = InStr(strString, strFind)
    intCount = intCount + 1
Wend

' append remainder upon failure of last InStr search
LOOP_ESCAPE:
strTemp = strTemp & strString
ReplaceWithin = strTemp
End Function



Note to Webmaster