Please Note: This article is written for users of the following Microsoft Word versions: 2007, 2010, 2013, and 2016. If you are using an earlier version (Word 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Word, click here: Highlight Words from a Word List.

Highlight Words from a Word List

by Allen Wyatt
(last updated January 6, 2018)

13

Paul has a document that he needs to check against a word list contained in another document. If the document being checked contains one of the words in the list, then the word in the document (not in the word list) needs to be highlighted by being made bold. The word list is large, on the order of 20,000 words, and Paul is wondering what the best way to do this is.

There are two ways you can proceed. The first is to write your own macro that will do the comparisons for you. If you put the words you want checked into a document named “checklist.doc” in the C: drive, then the following macro can be used:

Sub CompareWordList()
    Dim sCheckDoc As String
    Dim docRef As Document
    Dim docCurrent As Document
    Dim wrdRef As Object

    sCheckDoc = "c:\checklist.doc"
    Set docCurrent = Selection.Document
    Set docRef = Documents.Open(sCheckDoc)
    docCurrent.Activate

    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Replacement.Font.Bold = True
        .Replacement.Text = "^&"
        .Forward = True
        .Format = True
        .MatchWholeWord = True
        .MatchCase = True
        .MatchWildcards = False
    End With

    For Each wrdRef In docRef.Words
        If Asc(Left(wrdRef, 1)) > 32 Then
            With Selection.Find
                .Wrap = wdFindContinue
                .Text = wrdRef
                .Execute Replace:=wdReplaceAll
            End With
        End If
    Next wrdRef

    docRef.Close
    docCurrent.Activate
End Sub

All you need to do is have the document open that you want checked, and then run the macro. If the document containing the words to check is named differently or in a different location, just change the line that sets sCheckDoc so that it has a different full path name for the document.

Basically, the macro grabs each word from the word list and then does a Find and Replace operation using that word in the document. If you have many, many words in the word list, then the macro can take quite a while to run—20,000 Find and Replace operations is quite a few!

Note:

If you would like to know how to use the macros described on this page (or on any other page on the WordTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (1173) applies to Microsoft Word 2007, 2010, 2013, and 2016. You can find a version of this tip for the older menu interface of Word here: Highlight Words from a Word List.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Searching for Characters

When using pattern matching in a search, you can specify individual characters or ranges of characters you want matched ...

Discover More

Making Macros Run Faster

Designing a macro to make it run faster.

Discover More

Understanding Sections

Sections are handy if you want to subdivide a document so you can apply different document formatting to those ...

Discover More

Comprehensive VBA Guide Visual Basic for Applications (VBA) is the language used for writing macros in all Office programs. This complete guide shows both professionals and novices how to master VBA in order to customize the entire Office suite for their needs. Check out Mastering VBA for Office 2010 today!

More WordTips (ribbon)

Creating a New Document in VBA

When working with documents in a macro, it makes sense that you may need to create a document from time to time. Here's ...

Discover More

Moving the Insertion Point to the End of a Line

When writing a macro to process the text in a document, you may need to move the insertion point to the end of a line. ...

Discover More

Jumping to the Start or End of a Document

When creating macros, it is often necessary to move the insertion point around the document so that text can be processed ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 3 + 8?

2018-09-18 16:59:40

Allen

Grace,

You are missing a line from the macro:

Set docCurrent = Selection.Document

I didn't check for any other missing lines.

-Allen


2018-09-18 16:57:02

Grace

Hello!
I'm desperately trying to make this macro work, I've created a new macro, typed it in manually as i've read copy-paste sometimes doesn't work, i've double-checked for any typos and yet when i try to run it, an error pops up, saying this:

Run-time error '91':
Object variable or With block variable not set

and when i try to debug it, it highlights the 9th row of code, the one that says doc.Current.Activate.

i've googled it but I've not idea what to do, honestly, my field of expertise is the opposite of computers. If you could possibly bother to help me out here, I'd be truly grateful.
Thank you so much in advance!

ps: this is my current macro code:

Sub CompareWordLists()
'
' CompareWordLists Macro
'

Dim sCheckDoc As String
Dim docRef As Document
Dim docCurrent As Document
Dim wrdRef As Object

sCheckDoc = "C:\Users\Grace\Documents\Macros\testchecklist.docx"
Set docRef = Documents.Open(sCheckDoc)
docCurrent.Activate

With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = True
.Replacement.Text = "^&"
.Forward = True
.Format = True
.MatchWholeWord = False
.MatchCase = False
.MatchWildcards = False
End With

For Each wrdRef In docRef.Words
If Asc(Left(wrdRef, 1)) > 32 Then
With Selection.Find
.Wrap = wdFindContinue
.Text = Trim(wrdRef)
.Execute Replace:=wdReplaceAll
End With
End If
Next wrdRef

docRef.Close
docCurrent.Activate


End Sub


2018-06-13 03:28:16

Sean

Hi all,

Thanks heaps for the macro!
I'm learning coding in visual vba and I was wondering if we could modify this marcro to the form where it can search across multiple word files instead of one?

I applied the macro and it worked perfectly but I have got nearly 100 word documents that need to check against a word list, that means I will have to do the same step 100 times which is quite time consuming & troublesome.

I would appreciate, if you could help me with solving this matter.

Kindest,
Sean


2018-04-25 16:39:00

Paul

what is the second way?


2018-04-11 07:54:18

Paul

BRILLIANT Ken,

That worked "straight out of the box" Thank you so much.

Regards Paul


2018-04-11 05:14:09

Ken

Your problem is that the colour settings are outside the For Each wrdRef loop, they need to be set inside the loop.

Rather than use many Case statements, a neater way is to use an arrays of colour values and use NextColour to index them. Because the array indexes start at 0 NextColor also needs to start at 0. The colour values in the arrays can be obtained from the WdColorIndex enumeration. I suggest that you use the light grey colour instead of white because if the highlighting is removed then the text is invisible.

Dim hColor
Dim tColor
hColor = Array(7, 2, 4, 9, 13, 14, 11) ' etc for additional colors
tColor = Array(1, 16, 1, 16, 16, 1, 1) ' items must match the hcolor items
NextColour = 0

The For Each wrdRef loop now is:

For Each wrdRef In docRef.Words
If Asc(Left(wrdRef, 1)) > 32 Then
Options.DefaultHighlightColorIndex = hColor(NextColour)
With Selection.Find
.Wrap = wdFindContinue
.Text = Trim(wrdRef)
.Replacement.Font.ColorIndex = tColor(NextColour)
.Execute Replace:=wdReplaceAll
End With
NextColour = NextColour + 1
If NextColour > UBound(hColor) Then NextColour = 1
End If
Next wrdRef


2018-04-10 13:43:24

Paul

I have a document with usually 2 or 3 keywords, sometimes up to 10.
I wanted to highlight each in a different colour.
It seems the code below that I have modified selects every other TestWord, but I cannot see why.
On running the code it was clear black text on some colours was illegible.
My feeble attempt to use white text for some background colours has also failed.
Clearly, I am a baby macro writer~ can you set me straight?
Regards Paul

Sub TestWords()

Dim sCheckDoc As String
Dim docRef As Document
Dim docCurrent As Document
Dim wrdRef As Object
Dim NextColour As Integer
NextColour = 1

sCheckDoc = "C:\Users\user name\Documents\TestWords.doc"
Set docCurrent = Selection.Document
Set docRef = Documents.Open(sCheckDoc)
docCurrent.Activate
Options.DefaultHighlightColorIndex = wdYellow

With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = True
.Replacement.Text = "^&"
.Forward = True
.Format = True
.MatchWholeWord = True
.MatchCase = False
.MatchWildcards = False
End With

For Each wrdRef In docRef.Words
If Asc(Left(wrdRef, 1)) > 32 Then
With Selection.Find
.Wrap = wdFindContinue
.Text = Trim(wrdRef)
.Execute Replace:=wdReplaceAll
End With
End If

NextColour = NextColour + 1
Select Case NextColour
Case Is = 2
Options.DefaultHighlightColorIndex = wdBlue
Selection.Font.Color = wdWhite

Case Is = 3
Options.DefaultHighlightColorIndex = wdBrightGreen
Selection.Font.Color = wdBlack

Case Is = 4
Options.DefaultHighlightColorIndex = wdDarkBlue
Selection.Font.Color = wdWhite

Case Is = 5
Options.DefaultHighlightColorIndex = wdDarkRed
Selection.Font.Color = wdWhite

Case Is = 6
Options.DefaultHighlightColorIndex = wdDarkYellow
Selection.Font.Color = wdBlack

Case Is = 7
Options.DefaultHighlightColorIndex = wdGreen
Selection.Font.Color = wdBlack

Case Is = 8
Options.DefaultHighlightColorIndex = wdPink
Selection.Font.Color = wdBlack

Case Is = 9
Options.DefaultHighlightColorIndex = wdRed
Selection.Font.Color = wdWhite

Case Is = 10
Options.DefaultHighlightColorIndex = wdTeal
Selection.Font.Color = wdBlack

Case Is = 11
Options.DefaultHighlightColorIndex = wdTurquoise
Selection.Font.Color = wdBlack

Case Is = 12
Options.DefaultHighlightColorIndex = wdViolet
Selection.Font.Color = wdWhite

Case Is = 13
Options.DefaultHighlightColorIndex = wdWhite
Selection.Font.Color = wdBlack

Case Else
Options.DefaultHighlightColorIndex = wdGray50
Selection.Font.Color = wdWhite
End Select

Next wrdRef

docRef.Close
docCurrent.Activate

End Sub


2018-04-01 04:37:54

Paul

Ken, that works and is EXACTLY what I wanted.
Thank you for such a clear and quick reply.


2018-04-01 03:06:49

Ken Endacott

Paul

To highlight the words in yellow modify the macro as follows:

Immediately before the “With Selection.Find” statement insert the statement:
Options.DefaultHighlightColorIndex = wdYellow

Replace the statement “.Replacement.Font.Bold = True” with:
.Replacement.Highlight = True


2018-03-31 11:39:24

Paul

This is almost exactly what I wanted.
The only enhancement is I would like the replaced word to be highlighted yellow not shown in bold.
I lack the VBA skills to go that ~ any guidance gratefully accepted.


2018-02-20 03:07:45

Ken Endacott

The macro will only find words that have a following space which means that it misses words at the end of a sentence or paragraph or words that are immediately followed by a character such as semi-colon.

To fix this change the line:
.Text = wrdRef

to:
.Text = Trim(wrdRef)


2018-02-19 16:21:58

Keith

When I try to use this macro, it does partial words as well. I'm pretty new to macros and visual basic, but I noticed that it contains the code "matchwholeword = true". Is there a reason this isn't working for me?


2018-01-08 13:19:54

Sherry

So smart. This is excellent, thanks!


This Site

Got a version of Word that uses the ribbon interface (Word 2007 or later)? This site is for you! If you use an earlier version of Word, visit our WordTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.