PDA

View Full Version : How to use VBA to get strings of "\1" and "\2" found with wildcards



r591
04-22-2010, 11:51 PM
for example, I can found "1,234.56 USD" by Find "([0-9,.]@)^32(USD)" with wildcards enabled, and can replace it into "USD 1,234.56" by using "\2 \1".
The recorded macro is something like the following:
With Selection.Find
.text = "([0-9,.]@)^32(USD)"
.Replacement.text = "\2 \1"
.......
My question is:
Is there anyway to get the separate strings of "\1" and "\2" in VBA macro, such as:
MyStr1 = "\1" 'It should be "1,234.56" in this case
MyStr2 = "\2" 'It should be "USD" in this case

TonyJollans
04-23-2010, 12:10 PM
An interesting question, and the short answer is no.

You can, however, get it in a slightly roundabout way by replacing with \1, undoing, and replacing with \2, undoing, and then doing the full replace, something like this:

FindText = "([0-9,.]@)^32(USD)"
With ActiveDocument
With .Range
.Find.Execute FindText, , , True, , , , , , "\1"
MyStr1 = .Text
End With
.Undo
With .Range
.Find.Execute FindText, , , True, , , , , , "\2"
MyStr2 = .Text
End With
.Undo
.Range.Find.Execute FindText, , , True, , , , , , "\2 \1"
End With

r591
04-24-2010, 02:38 AM
It works great!
You are so smart, Tony.
Would you please recommend some good books on learning VBA?

TonyJollans
04-24-2010, 07:30 AM
Everybody has a different background, and learns in different ways and I don't know any general books I could really recommend as suitable for everyone, and most of what does exist is geared more to Excel than Word.

Although it does tend to get harder with each new release, my recommendation for most people is to use the macro recorder and to experiment with the code you get, using Help and/or the web to get specific information when you feel you need it. One of the real joys of VBA is that it is available to everybody and instant - you can try things out so easily, and if you're hopelessly stuck, there are boards such as this one where there are people only too happy to help.

r591
04-27-2010, 10:02 AM
Thanks for your advice.
I'll keep visiting your site from time to time.