Theoretically, it would be possible to find something, specifying a paragraph style as part of the replacement, and it should affect the entire paragraph. This has problems, however, when the style to be applied is a "linked style": a style that can be applied both as a paragraph and as a character style. Unfortunately, this is the case for all the built-in Heading styles. Applying such a style will not necessarily change the formatting of the text characters in the paragraph - direct formatting might override so that, while the paragraph is formatted with the style, visually the text may appear different.
Therefore, a simple Find/Replace will not suffice as additional steps become necessary to force the correct formatting.
The following works for me.
I assume the asterisks should be removed so set the replacement text to an empty string. Wildcards are not necessary in this scenario.
Execution is in a Do...Loop
so that each instance of the term is found individually and the replacement made. Then the style is applied and the range is selected in order to use the ClearCharacterDirectFormatting
method. This is the equivalent of pressing Ctrl+Spacebar as a user and forces the selection to display the paragraph style's formatting that may have been overlayed by direct font formatting.
It's then necessary to collapse the Range
before continuing the Find.
Sub FindAndReplace3Stars()
Dim myStoryRange As Range
Dim sFindTerm As String
sFindTerm = "***"
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = sFindTerm
.Replacement.Text = ""
.wrap = wdFindStop
Do While .Execute(Replace:=wdReplaceOne)
myStoryRange.style = wdStyleHeading3
myStoryRange.Select
With Selection
.ClearCharacterDirectFormatting
End With
myStoryRange.Collapse wdCollapseEnd
Loop
End With
Next myStoryRange
End Sub
Alternately, based on the original approach in the question using wildcards and selecting the entire paragraph (not sentence) could look like the following code sample. In this case, the search text is broken into two "expressions": the asterisks and the rest of the paragraph. The replacement text is the second expression (\@
- the rest of the paragraph) and in this scenario the style is applied as part of the replacement.
It's still necessary to select and clear the direct formatting in order to ensure that the style formatting is visible.
Sub FindAndReplace3Stars_Alternate()
Dim myStoryRange As Range
Dim sFindTerm As String
sFindTerm = "(\*\*\*)(?*^013)"
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = sFindTerm
.Replacement.Text = "\2"
.Replacement.style = wdStyleHeading3
.MatchWildcards = True
.wrap = wdFindStop
Do While .Execute(Replace:=wdReplaceOne)
myStoryRange.Select
With Selection
.ClearCharacterDirectFormatting
End With
myStoryRange.Collapse wdCollapseEnd
Loop
End With
Next myStoryRange
End Sub