Please Note: This article is written for users of the following Microsoft Word versions: 97, 2000, 2002, and 2003. If you are using a later version (Word 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Word, click here: Generating a Count of Word Occurrences.

Generating a Count of Word Occurrences

Written by Allen Wyatt (last updated January 27, 2022)
This tip applies to Word 97, 2000, 2002, and 2003


23

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.)
  2. Figure 1. The Replace tab of the Find and Replace dialog box.

  3. In the Find What box, enter the word or phrase you want counted.
  4. 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.)
  5. If you are searching for individual words, make sure you click the Find Whole Words Only check box.
  6. 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 VBA 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            '

    ' 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 http://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.

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 (1833) applies to Microsoft Word 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Word (Word 2007 and later) 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. ...

MORE FROM ALLEN

Using the Function Key Display Toolbar

Need to know what various function keys do? One easy way to find out is to use the Function Key Display toolbar, ...

Discover More

Printing Multiple Selections

Need to print several portions of a worksheet all on a single piece of paper? Here's an easy way you can get what you ...

Discover More

Section Breaks Changing On Their Own

Sometimes Word does things that just don't make sense. For instance, have you ever inserted a section break into your ...

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 (menu)

Word Count is Zero

If you use the Word Count tool and are surprised that it returns a count of 0, it could be because of what you selected ...

Discover More

Running Word Counts

Do you need to keep track of how many words are in your document? Word provides a tool to display a word count on demand, ...

Discover More

Word Count in Multiple Selections

Getting a word count for an entire document is easy. What you may not know is that some versions of Word can also provide ...

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}] (all 7 characters, in the sequence shown) 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 six more than 2?

2024-09-04 09:18:10

Paul Hanson

For the first macro, I added ".MatchCase = True" --- as shown below ---
but as for your actual question "how do I get the "case" to be a determining factor in the 2nd macro?" -- I don't know how to do that. I seem to have reached the limit of my ability to read macro code! <grin>
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
.MatchCase = True


2024-09-03 13:22:21

John Kranz

The script for counting ALL unique words in a document works great. However, I'm hoping it can be modified to show the word count for each word when it is capitalized and uncapitalized. (i.e. "boat" and "Boat"). The reason I hope this is possible is I'm editing a large document and there is some inconsistent case usage being used, so I'm trying to run a report on that. I hope this is something that can be provided!


2024-08-08 08:13:41

Dean

Allen, much thanks for the various useful Word Macros you have developed and shared.

There is another instance of these two Macros, also written by yourself, at a different URL:
https://wordribbon.tips.net/T010761_Generating_a_Count_of_Word_Occurrences.html

At first glance they appear to be the same. However, the WordFrequency() macros differ slightly in Code, and dramatically in behaviour.

The one here causes Errors if Option Explicit has been configured for the Module it is copied into.
The one at the other URL works Error-free.
Reason: two variables Dim aword and Dim tmpName are not defined here, but are within the other version.

By the way, this Comments submission screen included an 'Are you a human' test question: "What is three less than 4?"
The answer may appear to be simple enough. However, the question is pitched with one number expressed as text and the other as a number. So the human must guess as to whether a text or numeric format will be 'accepted' by the system as correct even though BOTH are. (Unless perhaps the system has been configured 'smart' enough to accept either format.)


2023-02-07 15:06:24

Andrew G.

ERROR IN PROGRAM
First thank you for this very useful macro!
In the program with the following caption:
" 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 VBA macro will do just that. "However when I ran it I noticed a slight error."

I noticed an error in code for the above section when I ran it.
While the program listed all the unique words from a to y, it missed out all the words starting with z except "z" itself.

I fixed this error in the following way. I replaced the following line:
If SingleWord < "a" Or SingleWord > "z" Then
with
If SingleWord < "a" Then
this adds some unwanted entries at the end of the list, after the words that begin with letter "z"
A better modification is:
If SingleWord < "a" Or Left(SingleWord,1) > "z" Then
There were no unwanted entries with this option.


2021-12-14 18:40:36

BThis

This would be awesome, but I can't get it to work. When I run the WordFrequency macro I get a Compile Error: Syntax Error on two lines:

j = MsgBox("The maximum array size has been exceeded. _
Increase maxwords.", vbOKOnly)

and

If (Not ByFreq And Words(l) < Words(k)) Or
(ByFreq And Freq(l) > Freq(k)) Then k = l

Any idea why? I'm running Word in Microsoft 365 Pro on Windows 10.
Thanks,
--BThis


2020-09-28 16:09:56

MUHAMMAD FARHAB

RESPECTED SIR.
I WANT TO KNOW THE CHARACTER COUNT OF A MICROSOFT WORD FILE THAT IS WRITTEN IN CHINESE.
THIS TRICK IS NOT WORKING WITH THE CHINESE MANUSCRIPT.
PLEASE GUIDE ME.

THANKS IN ADVANCE


2020-06-16 16:00:30

vsin

Hi , is it possible to breakdown the count of unique words in each heading, Like a word file has number of chapters and sub chapters, would it be possible to give the count per subchapter.


2020-05-24 10:08:44

Антон Анищенков

Hello and thank you for sharing this tip with us! But is it possible to use it for other languages? How?

Best regards,
Anton


2020-02-05 20:23:20

Andrew J

When I run the macro to find how many times each unique word appears, and choose to sort by frequency, the program runs until complete and then gives me a pop-up that says 8093 Unique words, but doesn't show me where to find the list and the count for those words? Am I possibly missing something?


2019-04-10 21:14:38

Erik

Hi, I'm trying to generate a sentence count... meaning, I have a set of keywords that I want to count as a unit (i.e. music theory would be one "word"). The division between keyword categories is a comma, so that's the signal to stop considering a word inside a category... is there any way I can do this? I'm sure there is I just can't find out how...


2019-03-06 17:32:48

fgjf fhjfhj

What if I dont know the word and want to find repeating words! serious what a waste of life you are


2019-03-05 08:06:20

Nadja

This is great! Is there any way to expand this to phrases (multiple words) as well?


2018-12-14 11:42:39

Sam

This tool is already helping me revise my dissertation. Thanks!


2018-09-06 06:25:08

R Raman

Thank you, but these macro (especially 2nd VBA macro) only works for Roman scripts, it does not work for other scripts such as Devanagri, Hindi etc.


2018-06-20 13:03:05

Mark Frunt

Thank you!! :)


2017-11-28 08:08:54

V.S.Rawat

They made it very long winded.

MS word/ excel is already showing a compulsory notification after each replacement, "These many replaced".

So they already have everything built in to count and show.

They should have given a single flag allowing users to see that notification.

thanks.


2017-10-07 03:28:24

Ben

This is great thank you. If I can add the status bar slows the macro down a lot. Comment it out for near instant speeds

Cheers!


2017-07-27 15:08:46

Alex

Just what I was looking for. Thank you Allen.


2017-04-09 01:29:35

Amir

Awesome, thank to so much!


2017-03-19 21:09:58

CESAR

EXCELLENT SOLUTION!!!! THANKS!!!!!!!!!


2017-03-15 17:59:57

Rick

Great article Allen. There's an effective online utility for doing this across multiple documents as well: http://bit.ly/2nbF4JU


2016-12-11 04:08:43

Dr.Pat Howden

Seasons Green Greetings Allen
Re Counting word or words, I seem to recall I emailed you this months ago. But in "Replace With", simply put same word or words you put in "Find What".

Try our 1-word Google:
DRPATSAWESOMELIBRARY & 2nd page show how to access & download.
All the best.


2016-12-10 17:36:29

Steve Wells

In Sub FindWords, there is a comment line that says:
' show the number of occurences

Occurrences is spelled correctly in the article title, but it is misspelled in the comment. Comment text does not effect the operation of the routine.


This Site

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

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