| Public Function Replace(sIn As String, sOld As String, sNew As String) _
As String
If sIn = "" Then
Exit Function
End If
If sOld = "" Then
Exit Function
End If
Dim colBefore As Collection
Set colBefore = New Collection
Dim nPos As Long
Dim nPosLast As Long
Dim nLen As Long
Dim vItem As Variant
nPosLast = 1
nPos = InStr(nPosLast, sIn, sOld)
Do While nPos <> 0
colBefore.Add Mid(sIn, nPosLast, (nPos) - nPosLast)
nPosLast = nPos + Len(sOld)
nPos = InStr(nPosLast, sIn, sOld)
Loop
Replace = Space(Len(sIn) + ((Len(sNew) - Len(sOld)) * _
colBefore.Count))
nPos = 1
For Each vItem In colBefore
nLen = Len(vItem)
If nLen > 0 Then
Mid(Replace, nPos, nLen) = vItem
nPos = nPos + nLen
End If
If sNew <> "" Then
Mid(Replace, nPos, Len(sNew)) = sNew
nPos = nPos + Len(sNew)
End If
Next
If nPosLast <= Len(sIn) Then
Mid(Replace, nPos) = Mid(sIn, nPosLast)
End If
Set colBefore = Nothing
End Function
|