PDA

View Full Version : Find-replace in Word so that it changes the formatting of the entire sentence/para



Davecogz84
11-13-2018, 08:00 AM
Hello world,

I'm pretty sure that I've done this before with Find-Replace (and have not needed to resort to "For each...next" expressions). I can't find any previous posts specifically relating to this:

- Suppose that you have a sentence like "VBAExpress is great." and somewhere else in the document "VBAExpress rocks!".
- I would like to do a find-replace in the document for all instances of "BAEx", for instance, and to make any para in which this is found italics.

My attempt (unsurprisingly) only italicizes the specific word searched for:

' Italicize BAEx paras
Sub BAEx()
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "BAEx"
.Replacement.Font.Italic = True
.Forward = True
.Wrap = wdFindContinue
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub


Any help would be much appreciated!

macropod
11-13-2018, 02:01 PM
The fundamental problem you'll have with a sentence-based Find/Replace is that neither Find/Replace nor VBA
have any idea what a grammatical sentence is. For example, consider the following:
Mr. Smith spent $1,234.56 at Dr. John's Grocery Store, to buy: 10.25kg of potatoes; 10kg of avocados; and 15.1kg of Mrs. Green's Mt. Pleasant macadamia nuts.
For you and me, that would count as one sentence; for VBA it counts as 5 sentences.

Paragraph-level actions, however, are simple and don't even require a macro. A wildcard Find/Replace would suffice, where:
Find = [!^13]@BAEx*^13
Replace = ^&
and the replace expression is set to italic.

Davecogz84
11-13-2018, 03:45 PM
Super, this works. Thank you! The sentences in my document happen to coincide with paragraphs, so I'm fine on that front.

I think I get all the wildcards except ^13. Why is that there?

macropod
11-13-2018, 04:08 PM
The [!^13] says to start at the first character that isn't a paragraph break. The *^13 says to find everything up to and including the next paragraph break.