0

Is it possible to use substitution patterns with RegExp objects in Word VBA? Could I search a document for a pattern with a bunch of parentheses and replace it with something like \4 \2? (I tried, but it used the literal string.)

Frungi
  • 506
  • 5
  • 16

2 Answers2

1

See this answer for information on RegEx with VBA. While this specific answer was written for Excel VBA specifically, it will still apply to word.

In the sample code, he sets MyRange = ActiveSheet.Range("A1") instead you could do, Set MyRange = ActiveDocument.Range(Start:=0, End:=Selection.End) and replace MyRange.Value with MyRange.Text

Existing answers are a powerful tool. Sometimes it's helpful to look at Excel VBA code for all the other Microsoft Applications as Excel is the tool which has code written for it the most.

Community
  • 1
  • 1
JDB_Dragon
  • 162
  • 10
  • I think "Example 4" in [this answer](http://stackoverflow.com/a/22542835/1015293) is along the lines of what I'm looking for, right? Thanks, I'll try that. – Frungi Dec 21 '15 at 19:21
1

Word, itself, does not support RegEx. It has its own Wildcard functionality. This is similar to RegEx but not identical. You can see the possibilities by clicking "More" in the Replace dialog box (Ctrl+H), activating the "Wildcard" checkbox, then looking at the list in "Special". If you search the Internet for a set of terms like - Word Find Replace Wildcard - you'll turn up lots of examples and discussions.

The approach suggested by JDB_Dragon usually is often not satisfactory in Word because manipulating just the string then writing it back to the document loses all formatting.

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
  • Word doesn’t, but VBA in Word does. That’s why I specified `RegExp` objects. – Frungi Dec 21 '15 at 00:59
  • No, VBA does NOT have RegEx. You can add the reference to a library that provides RegEx to your VBA code, but it's not part of VBA. And if you distribute your code you need to make sure the target computer has that library, otherwise your code can't run. And, as I said, if retaining or applying Word formatting is necessary, RegEx will not/cannot work. – Cindy Meister Dec 21 '15 at 15:11
  • Oh, my mistake; I figured that if I'm able to use it in VBA after ticking a box, it must be part of VBA (and I thought it would have been clear what I was referring to when I first mentioned it). And no, formatting is irrelevant for my case. – Frungi Dec 21 '15 at 19:26