Searching a document for multiple terms in VBA?
- by Tony
I'm trying to create a macro to be used in Microsoft Word 2007 that will search a document for multiple keywords (string variables) located in an external Excel file (the reason for having it in an external file is that the terms will often be changed and updated). I've figured out how to search a document paragraph by paragraph for a single term and color every instance of that term, and I assumed that the proper method would be to use a dynamic array as the search term variable.
The question is: how do I get the macro to create an array containing all the terms from an external file and search each paragraph for each and every term?
This is what I have so far:
Sub SearchForMultipleTerms()
'
Dim SearchTerm As String 'declare search term
SearchTerm = InputBox("What are you looking for?") 'prompt for term. this should be removed, as the terms should come from an external XLS file rather than user input.
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatti…
With Selection.Find
.Text = SearchTerm 'find the term!
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
While Selection.Find.Execute
Selection.GoTo What:=wdGoToBookmark, Name:="\Para" 'select paragraph
Selection.Font.Color = wdColorGray40 'color paragraph
Selection.MoveDown Unit:=wdParagraph, Count:=1 'move to next paragraph
Wend
End Sub
Thanks for looking!