Option Explicit
Option Base 0
#If Not VB6 Then
Public Const vbBinaryCompare As Long = 0
Public Const vbTextCompare As Long = 1
Public Function Replace(Expression As Variant, Find As Variant, ReplaceWith As Variant, Optional Start As Long = 1, Optional Count As Long = -1, Optional Compare As Long)
Dim byExpression() As Byte
Dim byFind() As Byte
Dim byRplcW() As Byte
Dim byTmp() As Byte
Dim lExpPos As Long
Dim lFindPos As Long
Dim lRplcPos As Long
Dim lTmpPos As Long
Dim lExprLB As Long
Dim lExprUB As Long
Dim lFindUB As Long
Dim lRplcUB As Long
Dim lTmpUB As Long
Dim sExpr As String
Dim sFind As String
Dim lRplcCnt As Long
Const lNoReplace_c As Long = -1
Const lZero_c As Long = 0
Const lArrayOffset_c As Long = 1
Const lUnicodeOffset_c As Long = 2
If Count = lZero_c Then Exit Function
If Compare = vbBinaryCompare Then
byExpression = CStr(Expression)
byFind = CStr(Find)
Else
sExpr = VBA.LCase$(CStr(Expression))
sFind = VBA.LCase$(CStr(Find))
byExpression = sExpr
byFind = sFind
End If
If UBound(byFind) < lZero_c Then
Replace = CStr(byExpression)
Exit Function
End If
lExprUB = UBound(byExpression)
If Start > lExprUB + lArrayOffset_c Then Exit Function
lFindUB = UBound(byFind)
byRplcW = CStr(ReplaceWith)
lRplcUB = UBound(byRplcW)
lExprLB = Start - lArrayOffset_c
Do
For lExpPos = lExprLB To lExprUB Step lUnicodeOffset_c
If byExpression(lExpPos) = byFind(lFindPos) Then
lFindPos = lFindPos + lUnicodeOffset_c
If lFindPos > lFindUB Then
lFindPos = lZero_c
Exit For
End If
Else
lFindPos = lZero_c
End If
Next lExpPos
If lExpPos > lExprUB Then
Exit Do
Else
If Compare = vbTextCompare Then
byExpression = sExpr
byFind = sFind
End If
lExprLB = lExpPos - lFindUB + lRplcUB
lTmpUB = lExprUB - lFindUB + lRplcUB
ReDim byTmp(lTmpUB) As Byte
For lTmpPos = lZero_c To lExpPos - lFindUB Step lUnicodeOffset_c
byTmp(lTmpPos) = byExpression(lTmpPos)
Next lTmpPos
lRplcPos = lZero_c
For lTmpPos = lTmpPos To lTmpPos + lRplcUB Step lUnicodeOffset_c
byTmp(lTmpPos) = byRplcW(lRplcPos)
lRplcPos = lRplcPos + lUnicodeOffset_c
Next lTmpPos
lExpPos = lExpPos + lUnicodeOffset_c
For lTmpPos = lTmpPos To lTmpUB Step lUnicodeOffset_c
byTmp(lTmpPos) = byExpression(lExpPos)
lExpPos = lExpPos + lUnicodeOffset_c
Next lTmpPos
byExpression = byTmp
sExpr = CStr(byExpression)
lExprUB = UBound(byExpression)
If Count <> lNoReplace_c Then
lRplcCnt = lRplcCnt + lArrayOffset_c
If lRplcCnt = Start Then Exit Do
End If
End If
Loop
Replace = CStr(byExpression)
End Function
#End If
|