Replace is probably the wrong tool fo rthe job you are trying to do.
If the second occurrence of 'xx' is always 'xx' in position 10 then you would
be advised to use Mid(). This depends on you replacing a known expression of
a known size at a known location with another known value.
Mid(oldString, 10,2) = "xy" - note you must use Mid() NOT Mid$()
If, however, as I suspect you, want to remove the 2nd occurrence of a known
string then the most efficient is to use Regular expressions. Here's a
function which'll allow you to replace the second occurrence of any sub-
string in any string, with something else.
Your example would use it like this:
oldString = "ab xx cd xx efgh"
lookFor = "xx"
changeto = "xy"
newString = Replace2nd(oldString , lookFor, changeto)
Function Replace2nd(strIn as string, _
strFind as string, _
strReplace as string _
) as string
Dim re as Object
Set re = CreateObject("VBScript.RegExp")
re.IgnoreCase = True 'alter as required, or change to use an additional
Optional parameter.
re.Pattern = "(.*)(" & strFind & ")(.*)( & strFind & )(.*)" ' Creates a
pattern of "(.*)(xx)(.*)(xx)(.*)"
If re.test(strIn ,"$1$2$3" & strReplace & "$5") Then
Replace2nd = re.Replace(strIn ,"$1$2$3" & strReplace & "$5")
Else
Replace2nd = strIn
End If
End Function
This has the added advantage that instances of the search string - "xx" in
this case - anywhere in the oldString - it will work even if the oldString
were just "xxxx".
Regular expressions are well worth the investment in time to learn as they
are by far the most efficient way to do complex string manipulation.
Hi,
I've a problem using the Replace function in VBA. I've the string "ab xx cd
[quoted text clipped - 10 lines]