title: How can I replace a Microsoft Word character style within a range/selection in VBA?
body: <p>I'm working on a Word 2007 template with a macro that will apply character styles to the selected text. It seemed that the Find/Replace feature would be a good place to start, but I think I've found a bug/limitation that prevents the macro from working as desired.</p>
  
  <p>Here's my vba code:</p>
  
  <pre><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
  </code></pre>
  
  <p>If I create a test document that contains a few paragraphs and select a few words in one of the paragraphs, then run the macro, the "Emphasis" style is applied not only to the selection, but beyond the end of the selection to the end of the document.</p>
  
  <p>This behavior is the same using the actual GUI Find/Replace tool.</p>
  
  <p><strong>My question is:</strong> How can I overcome this bug/limitation and apply the character style <strong>ONLY</strong> within the selection/range?</p>
  
  <p><strong><em>A little more information:</em></strong><br>
  What I really need the macro to do is apply certain formatting to the entire selection while maintaining the existing character styles in the selection. For example, if the selected text contains the Bold character style, the Italic character style, and the rest of it is Default Paragraph Font, the macro should replace Bold with "Revised Bold", replace "Italic" with "Revised Italic", and replace "Default Paragraph Font" with "Revised". That way, when I use the companion macro to "undo" the action of this macro, the original character styles (Bold, Italic, Default Paragraph Font) can be replaced.</p>
  
  <p><strong><em>SOLVED:</em></strong><br>
  Here is the solution I finally arrived at:</p>
  
  <pre><code>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
  </code></pre>