sing VBScript Regex in Word VBA

P

Poseur

Someone might find this handy.
Having gotten comfortable using the VBScript RegExp Object via
COM in Excel, I wanted to use it also in Word just as a handy
little precise and efficient search and replace utility. Could
not find any suggestions on how to do that exactly. Googling
these groups, I saw a lot of references to Graham Mayor's
article "Finding and Replacing Characters Using Wildcards"
(http://www.mvps.org/word/FAQs/General/UsingWildcards.htm) but
after I read it it seemed I'd have to learn 2 sets of meta-
characters, a different behavior (non-greedy by default) and
the wildcard set does not offer any lookaround facility.
So, I piddled and I finally got it. An interactive fxn
(procedure) I put in my custom menu. It is very quick and I
can be very precise:

For a Selection:
Sub RegExInterSel()
Dim regEx As VBScript_RegExp_55.RegExp
Dim withWhat As String
Dim newStr As String
Set regEx = New VBScript_RegExp_55.RegExp
With regEx
.Pattern = InputBox("Replace What?")
.Global = True
.IgnoreCase = False
End With
withWhat = InputBox("With What?")
If regEx.Test(Selection.Text) Then
Selection.Text = regEx.Replace(Selection.Text,withWhat)
End If
End Sub

For the whole document:
Sub RegExInterAll()
Dim regEx As VBScript_RegExp_55.RegExp
Dim withWhat As String
Dim Sentence As Range
Set regEx = New VBScript_RegExp_55.RegExp
With regEx
.Pattern = InputBox("Replace What?")
.Global = True
.IgnoreCase = False
End With
withWhat = InputBox("With What?")
For Each Sentence In ActiveDocument.Range.Sentences
If regEx.Test(Sentence.Text) Then
Sentence.Text = regEx.Replace(Sentence.Text, _
withWhat)
End If
Next Sentence
End Sub

There are probly some inefficiences in the above, particular
the latter using the Range object. Had trouble with that one.
If I "replaced" using large Range text properties for the
entire document, all formatting went away and I got a text
file. This works.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top