I am working on a Word 2007 template with a macro that will apply character styles to the selected text. The Find / Replace function seemed to be a good place to start, but I think I found an error / limitation that prevents the macro from working as desired.
Here is my vba code:
Sub restyleSelection() Dim r As Range Set r = Selection.Range With r.Find .Style = ActiveDocument.Styles("Default Paragraph Font") .Text = "" .Replacement.Text = "" .Replacement.Style = ActiveDocument.Styles("Emphasis") .Forward = True .Wrap = wdFindStop .Format = True .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False .Execute Replace:=wdReplaceAll End With End Sub
If I create a test document containing several paragraphs and select several words in one of the paragraphs, then run the macro, the Accent style applies not only to the selection, but also to the end of the selection at the end of the document.
This is the same as the actual GUI search / replace tool.
My question is: How can I overcome this error / limitation and apply the character style ONLY within the selection / range?
A bit more info:
What I really need to do the macro is to apply certain formatting to the whole selection, while preserving the existing character styles. For example, if the selected text contains a bold style, an Italian character style, and the rest is the default font, the macro should replace Bold with “Revised Bold”, replace “Italic” with “Revised Italic” and replace “Default Paragraph Font” with "Revised." Thus, when I use the companion macro to "undo" the action of this macro, I can replace the original character styles (Bold, Italic, Default Paragraph Font).
SOLVE:
Here is the solution I finally came to:
Sub applyNewRevisedText Dim r As Range ' Create a new Range object Set r = Selection.Range ' Assign the current selection to the Range Dim rng As Range For Each rng In r.Words Set rngStyle = rng.Style Select Case rngStyle Case "Bold" rng.Style = ActiveDocument.Styles("New/Revised Text Bold") Case "Italic" rng.Style = ActiveDocument.Styles("New/Revised Text Emphasis") Case Else rng.Style = ActiveDocument.Styles("New/Revised Text") End Select Next rng End Sub
source share