Microsoft Word - Replace vba text string using wildcards

Asked By John Wirth on 06-Jul-13 01:28 PM
OK, I want to replace part of a vba string using wildcard *, and I know that the vba replace doesn't support this. Are there any alternatives? What I want to do is replace [*] where * is an unspecified number of characters. What I replace it with will be variable as it will be from a userform textbox. All I can find on the internet is code using Regex which is way beyond me.
Replacing the text between the []'s would also be acceptable, provided it allowed for the length of that text to be unspecified.
Robbe Morris replied to John Wirth on 06-Jul-13 05:01 PM
If you are using brackets (or some other containing set of characters), you could use the MID function and INSTR functions in VBA to find the starting and ending position of your brackets.  You'd use the MID function to grab the first part of the string up to the first bracket.  Then, grab the end portion of the string from the second bracket until the end.
Now, you'd concatenate string1 + textboxvalue + string2 to get your new value.  There are more refined ways of doing this but this will at least get you started.
John Wirth replied to Robbe Morris on 11-Jul-13 03:34 AM
Thanks Robbe. I did it using this code:

Sub BraceReplace()
Dim Str As String
Dim P1 As Long
Dim P2 As Long
Str = ActiveDocument.Name
P1 = InStr(S, "[")
P2 = InStr(S, "]")
S = Left(S, P1) & "replaced text" & Mid(S, P2)
End Sub
Robbe Morris replied to John Wirth on 11-Jul-13 08:00 AM
You'll want to make sure that P1 and P2 > -1 prior to executing the MID.  Otherwise, you'll generate runtime errors.
John Wirth replied to Robbe Morris on 13-Jul-13 03:02 AM
Thanks Robbe, but I don't understand the position of a character in a string could be anything less than 1. Could you explain?
Robbe Morris replied to John Wirth on 13-Jul-13 10:05 AM
If the string does not contain a [ or ] in your case, that function will return -1 indicating that it isn't there.  String manipulation functions will throw errors if you try to access a position that doesn't exist like -1.

Defensive programming teaches you to assume the possibility of failure and handle it accordingly.  This avoids untrapped errors at runtime and program crashing.  This is especially true of functions "you" think should never fail because the incoming parameter will "always" be populated properly.
John Wirth replied to Robbe Morris on 15-Jul-13 03:58 AM
Thanks Robbe, I understand now- the error handling would be my next stage once I had found how to do what I needed to do.

 I tried running the code with a document that had no "[" or "]" and it threw an error of course. I then amended it so that it it showed the position of "[" in a message box- it showed the position as zero.