Generating a Count of Word Occurrences (Microsoft Word)

Best choice for browsing
Browse from Singapore
Browse from Russian Federation
Browse from France
Browse from India

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: Generating a Count of Word Occurrences.

# Generating a Count of Word Occurrences

by Allen Wyatt
(last updated October 28, 2017)

6

As you are analyzing your documents, you may wonder if there is a way to create a count of the number of words in the document. Unfortunately, Word doesn't include such a feature, but there are a couple of things you can do.

First, if you want to know the number of times a specific word or phrase is used, you can follow these steps:

1. Press Ctrl+H to display the Replace tab of the Find and Replace dialog box. (See Figure 1.)

Figure 1. The Replace tab of the Find and Replace dialog box.

2. In the Find What box, enter the word or phrase you want counted.
3. In the Replace With box, enter ^&. This character sequence tells Word that you want to replace what you find with whatever you placed in the Find What box. (In other words, you are replacing the word or phrase with itself.)
4. If you are searching for individual words, make sure you click the Find Whole Words Only check box.
5. Click on Replace All. Word makes the replacements and shows you how many instances it replaced. That is the number you want.

This approach works great if you just have one or two words or phrases you want to know about. You can automate the process a bit by using a macro to search through the document and count for you. The following macro prompts the user for a word, and then counts the number of times that word appears in the document. It will continue to ask for another word until the user clicks on the Cancel button.

    Sub FindWords()
        Dim sResponse As String
        Dim iCount As Integer

        ' Input different words until the user clicks cancel
        Do
            ' Identify the word to count
            sResponse = InputBox( _
              Prompt:="What word do you want to count?", _
              Title:="Count Words", Default:="")

            If sResponse > "" Then
                ' Set the counter to zero for each loop
                iCount = 0
                Application.ScreenUpdating = False
                With Selection
                    .HomeKey Unit:=wdStory
                    With .Find
                        .ClearFormatting
                        .Text = sResponse
                        ' Loop until Word can no longer
                        ' find the search string and
                        ' count each instance
                        Do While .Execute
                            iCount = iCount + 1
                            Selection.MoveRight
                        Loop
                    End With
                    ' show the number of occurences
                    MsgBox sResponse & " appears " & iCount & " times"
                End With
                Application.ScreenUpdating = True
            End If
        Loop While sResponse <> ""
    End Sub

If you want to determine all the unique words in a document, along with how many times each of them appears in the document, then a different approach is needed. The following macro will do just that.

    Sub WordFrequency()
        Const maxwords = 9000          'Maximum unique words allowed
        Dim SingleWord As String       'Raw word pulled from doc
        Dim Words(maxwords) As String  'Array to hold unique words
        Dim Freq(maxwords) As Integer  'Frequency counter for unique words
        Dim WordNum As Integer         'Number of unique words
        Dim ByFreq As Boolean          'Flag for sorting order
        Dim ttlwds As Long             'Total words in the document
        Dim Excludes As String         'Words to be excluded
        Dim Found As Boolean           'Temporary flag
        Dim j, k, l, Temp As Integer   'Temporary variables
        Dim ans As String              'How user wants to sort results
        Dim tword As String            '
        Dim aword As Object            '
        Dim tmpName As String          '

        ' Set up excluded words
        Excludes = "[the][a][of][is][to][for][by][be][and][are]"

        ' Find out how to sort
        ByFreq = True
        ans = InputBox("Sort by WORD or by FREQ?", "Sort order", "WORD")
        If ans = "" Then End
        If UCase(ans) = "WORD" Then
            ByFreq = False
        End If

        Selection.HomeKey Unit:=wdStory
        System.Cursor = wdCursorWait
        WordNum = 0
        ttlwds = ActiveDocument.Words.Count

        ' Control the repeat
        For Each aword In ActiveDocument.Words
            SingleWord = Trim(LCase(aword))
            'Out of range?
            If SingleWord < "a" Or SingleWord > "z" Then
                SingleWord = ""
            End If
            'On exclude list?
            If InStr(Excludes, "[" & SingleWord & "]") Then
                SingleWord = ""
            End If
            If Len(SingleWord) > 0 Then
                Found = False
                For j = 1 To WordNum
                    If Words(j) = SingleWord Then
                        Freq(j) = Freq(j) + 1
                        Found = True
                        Exit For
                    End If
                Next j
                If Not Found Then
                    WordNum = WordNum + 1
                    Words(WordNum) = SingleWord
                    Freq(WordNum) = 1
                End If
                If WordNum > maxwords - 1 Then
                    j = MsgBox("Too many words.", vbOKOnly)
                    Exit For
                End If
            End If
            ttlwds = ttlwds - 1
            StatusBar = "Remaining: " & ttlwds & ", Unique: " & WordNum
        Next aword

        ' Now sort it into word order
        For j = 1 To WordNum - 1
            k = j
            For l = j + 1 To WordNum
                If (Not ByFreq And Words(l) < Words(k)) _
                  Or (ByFreq And Freq(l) > Freq(k)) Then k = l
            Next l
            If k <> j Then
                tword = Words(j)
                Words(j) = Words(k)
                Words(k) = tword
                Temp = Freq(j)
                Freq(j) = Freq(k)
                Freq(k) = Temp
            End If
            StatusBar = "Sorting: " & WordNum - j
        Next j

        ' Now write out the results
        tmpName = ActiveDocument.AttachedTemplate.FullName
        Documents.Add Template:=tmpName, NewTemplate:=False
        Selection.ParagraphFormat.TabStops.ClearAll
        With Selection
            For j = 1 To WordNum
                .TypeText Text:=Trim(Str(Freq(j))) _
                  & vbTab & Words(j) & vbCrLf
            Next j
        End With
        System.Cursor = wdCursorNormal
        j = MsgBox("There were " & Trim(Str(WordNum)) & _
          " different words ", vbOKOnly, "Finished")
    End Sub

When you open a document and run this macro, you are asked if you want to create a list sorted by word or by frequency. If you choose word, then the resulting list is shown in alphabetical order. If you choose frequency, then the resulting list is in descending order based on how many times the word appeared in the document.

While the macro is running, the status bar indicates what is happening. Depending on the size of your document and the speed of your computer, the macro may take a while to complete. (I ran it with a 719-page document with over 349,000 words and it took about five minutes to complete.)

Note that there is a line in the macro that sets a value in the Excludes string. This string contains words that the macro will ignore when putting together the word list. If you want to add words to the exclusion list, simply add them to the string, between [square brackets]. Also, make sure the exclusion words are in lowercase.

If you don't like to use macros for some reason, there are other programs you can use to create word counts. For instance, the NoteTab text editor (the "light" version can be downloaded free at https://www.notetab.com/) includes a feature that provides a word count. All you need to do is copy your entire document and paste it into NoteTab. Then, within NoteTab, choose Tools | Text Statistics | More. It presents an analysis of the word frequency, including percentages.

WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (10761) 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: Generating a Count of Word Occurrences.

##### 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. Learn more about Allen...

##### MORE FROM ALLEN

The Line that Won't Go Away

Have you ever had a line appear on your document that you can't seem to get rid of? It could be due to a built-in ...

Discover More

Automatically Creating Charts for Individual Rows in a Data Table

If you have a lot of records in a data table, you may want to create individual charts based on the information in those ...

Discover More

Automatic Row Height for Wrapped Text

When you format a cell so that the information within it can wrap to multiple lines, you may be surprised if Excel ...

Discover More

Do More in Less Time! Are you ready to harness the full power of Word 2013 to create professional documents? In this comprehensive guide you'll learn the skills and techniques for efficiently building the documents you need for your professional and your personal life. Check out Word 2013 In Depth today!

##### More WordTips (ribbon)

Mass Search and Replace

If you need to change information in dozens or even hundreds of documents, the task can seem insurmountable. Here's a way ...

Discover More

Creating a Lorem Ipsum Tool

When editing, you may need random placeholder text inserted in your document. Word provides a couple of ways you can do ...

Discover More

Comparing Document Versions

Do you need to compare two versions of a document to each other? Word provides a tool that can make this easy, as ...

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.

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

##### 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.

Source

(gif, jpeg or png only, 5MB maximum file size)

Source

(gif, jpeg or png only, 5MB maximum file size)

Source

(gif, jpeg or png only, 5MB maximum file size)

Notify me about new comments ONLY FOR THIS TIP

Notify me about new comments ANYWHERE ON THIS SITE

Hide my email address

What is 2 + 4?

2018-03-05 21:37:58

matthew

Sorry for the probably ignorant question, but how exactly do I input this macro into word once I've clicked "record macro." Do I need to type it all in? Is there a different menu I open to input it? I've found a couple instructional things about inputting macros, but none of the examples used anything like this. Any guidance would be much appreciated. Thank you

2017-12-10 05:22:10

Shahriyar

@James Thomas
This page includes good information on how to use Macros' code work into MS Word.
http://www.gmayor.com/installing_macro.htm

2017-12-10 05:19:04

Shahriyar

Thanks man! I used longer code to auto find duplicates, your solution is irreplaceable!! Keep up good work +

2017-10-28 12:03:31

Patricia Boyd

Thanks for this info. Another nonmacro way is to press Ctrl + F to open the Find box. Then type in the word you want to find. Then click on the "Find in" dropdown menu, and pick "main document." (Or, press Alt+i, m) This will tell you the number of occurrences of the word. (('d hesitate to use the "Replace" method you describe, because I'm usually editing for a client, and I don't want to show the replacement of the word with itself either as a tracked change or a non-tracked changed. If I turn track changes off, I run the risk of hiding the fact that I inserted a term as a track change. If I turn track changes on, then every single occurrence is going to show up as a tracked insertion of the same word.

2017-10-28 06:07:41

Ian

Thank you for these wonderful tips!

2017-10-28 05:16:16

James Thomas

That Macro looks amazing. And scary. Do you have Tips page that tells us how to get this Macro into our MS Word programs? Thanks - text stats are quite important to me and I had no idea they could be done within Word. Many 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

Changing Strikethrough Lines

Printing Color Separations with VBA

Maintaining Delivery Address Information for Envelopes

Unwanted Styles

Turning Off Automatic Bulleted Lists

Displaying the Document Map

Creating Multiple Blank Documents in One Step

Removing HTML Tags from Text

##### 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.

##### Links and Sharing

- WordTips FAQ
- Ask a Question
- Make a Comment
- Free Business Forms
- Free Calendars
- AddThis Sharing Buttons
  Share to Facebook
  Share to Twitter
  Share to Pinterest
  Share to Google+
  Share to Email
  Share to More

Copyright © 2018 Sharon Parq Associates, Inc.