title: MS Word VBA - Finding a word and changing its style
body: <p>I'm trying to find all instances of key words in a MS Word document and change their style. The key words are stored within an array and I want to change the style of the particular word only. Ideally this would happen as I type but that is not crucial.</p>
  
  <p>Attempt 1 - Based on recording a macro and changing the search term</p>
  
  <pre><code>Sub Woohoo()
  Dim mykeywords
  mykeywords= Array("word1","word2","word3")
  
  For myword= LBound(mykeywords) To UBound(mykeywords)
  
      Selection.Find.ClearFormatting
      Selection.Find.Replacement.ClearFormatting
      Selection.Find.Replacement.Style = ActiveDocument.Styles("NewStyle")
      With Selection.Find
          .Text = mykeywords(myword)
          .Replacement.Text = mykeywords(myword)
          .Forward = True
          .Wrap = wdFindContinue
          .Format = True
          .MatchCase = False
          .MatchWholeWord = True
          .MatchWildcards = False
          .MatchSoundsLike = False
          .MatchAllWordForms = False
      End With
      Selection.Find.Execute Replace:=wdReplaceAll
  Next
  
  End Sub
  </code></pre>
  
  <p>This changes the style of the entire paragraph where the words are in.</p>
  
  <p>Attempt 2 - Based on this question here <a href="https://stackoverflow.com/questions/8748240/how-can-i-replace-a-microsoft-word-character-style-within-a-range-selection-in-v">How can I replace a Microsoft Word character style within a range/selection in VBA?</a>: </p>
  
  <pre><code>Sub FnR2()
  Dim rng As Range
  Dim mykeywords
  mykeywords = Array("word1","word2","word3")
  
  For nKey = LBound(mykeywords) To UBound(mykeywords)
  For Each rng In ActiveDocument.Words
      If IsInArray(rng, mykeywords(nKey)) Then
          rng.Style = ActiveDocument.Styles("NewStyle")
      End If
  Next
  Next
  
  End Sub
  </code></pre>
  
  <p>This finds words that are in single lines but skips the words that are within a paragraph for some reason, e.g. it finds </p>
  
  <pre><code>Some text
  word1
  more text
  </code></pre>
  
  <p>but not</p>
  
  <pre><code>Some text before word1 means that the code above doesn't change the format
  Word1 also isn't changed in this instance
  </code></pre>
  
  <p>Attempt 3 - AutoCorrect; not actually tried:</p>
  
  <p>As an alternative I was thinking to use AutoCorrect. However I have more than 100 keywords and have no idea how to add this to the AutoCorrect list automatically (I'm fairly VBA illiterate). The other problem I would see with this approach is that I believe that AutoCorrect is global, whereas I need this only to work for a specific document.</p>