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: Occurrences of a Text String within a Document.

Occurrences of a Text String within a Document

Written by Allen Wyatt (last updated February 16, 2019)
This tip applies to Word 97, 2000, 2002, and 2003


5

Marc is looking for the fastest, most efficient way—within a macro—to determine a count of how many times a particular text string occurs within a document. Unfortunately there is no way to do this with a simple command or two; instead you need to "step through" a document using the Find and Replace feature of Word.

First, make a temporary copy of your document so that you don't run the risk of messing up your original document. Then use a variable in your macro to count the number of times the desired text gets replaced, and increment the variable every time a replacement occurs. In the following example, the number of times will end up in the variable Replacements. You can then use the value or convert the value to a string to display it.

Sub CountReplacements
    Dim Replacements As Integer

    Replacements = 0
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = InputBox("Enter the text you want to find:")
        .Replacement.Text = InputBox("Enter the replacement text:")
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .Execute Replace:=wdReplaceOne

        Do Until Not .Found
            .Execute Replace:=wdReplaceOne
            Replacements = Replacements + 1
            Selection.MoveRight Unit:=wdCharacter, Count:=1
        Loop

        If Replacements <> 0 Then
            MsgBox _
              "" & .Text & " has been replaced " & _
              CStr(Replacements) & " times with " & _
              .Replacement.Text
        Else
            MsgBox .Text & " was not found in the document/selection."
        End If
    End With
End Sub

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 (3368) 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: Occurrences of a Text String within a Document.

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

Changing the Language Setting for All Document Text

Word supports a number of different languages for documents you create. If you need to routinely change the language used ...

Discover More

Deleting Everything Except Formulas

Need to get rid of everything in a worksheet except the formulas? It's easier to make this huge change than you think it is.

Discover More

Ribbon Acting Strangely

The ribbon is the place where Word stores all the tools you need to work with your documents. What happens when the ...

Discover More

The First and Last Word on Word! Bestselling For Dummies author Dan Gookin puts his usual fun and friendly candor back to work to show you how to navigate Word 2013. Spend more time working and less time trying to figure it all out! Check out Word 2013 For Dummies today!

More WordTips (menu)

Detecting an Open Dialog Box

Macros can be used to perform all sorts of tasks within Word. Some tasks can even occur at whatever time interval you ...

Discover More

Extracting INCLUDEPICTURE File Names

If you use the INCLUDEPICTURE field to add images to your document, you may love the macro in this tip. It allows you to ...

Discover More

Editing Word's Built-in Commands

Want to configure Word to do just what you want it to? You can even go so far as to change the actual way in which Word ...

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 two more than 7?

2022-03-25 05:17:22

Ken Endacott

Here is another macro that will count occurrences of a phrase. It is about 10 times faster on long documents and is safer as it does not change the document.

Sub countStr()
Dim txt As String
txt = InputBox("Enter the text you want to find:")
MsgBox CountStrings(txt) & " occurrences of " & txt
End Sub

Function CountStrings(str As String) As Long
Dim count As Long
Dim aRange As Range
count = 0
Set aRange = ActiveDocument.Range
With aRange.Find
.ClearFormatting
.Text = str
.MatchCase = False ' True if you want exact case match
End With
Do
If aRange.Find.Execute(Replace:=wdReplaceNone) Then
count = count + 1
aRange.Collapse direction:=wdCollapseEnd
aRange.End = ActiveDocument.Range.End
Else: Exit Do
End If
Loop
CountStrings = count
End Function


2022-03-24 16:19:44

Ric D

Or an even easier way:

bigStr = activedocument.range.text
count = (len(bigStr) - len(replace(bigStr,subStr,"")) / len(subStr)
bigStr="" 'empty this out just to free the memory...

Or in just one line:
count = (len(activedocument.range.text) - len(replace(activedocument.range.text, subStr, "")) / len(subStr)


2022-03-24 16:09:56

Ric D

I was also looking for a simple function; thanks for confirming it doesn't exist!

However, there's a slightly simpler way to get the count than your function. Replacement is not necessary. The key is using selection.find.wrap = wdStop, and starting by moving to the top of the document. Then you can simply execute the find until .found = false and extract the count.
I started with your code, and converted it to a function:

Function countOccurrences(ByVal str2find As String)
Dim count As Integer
Dim rng As Range

Set rng = Selection.Range 'Hold you place!

countOccurrences = 0
Selection.HomeKey unit:=wdStory
Selection.Find.ClearFormatting
With Selection.Find
.Text = str2find
.Forward = True
.Wrap = wdFindStop
.Format = False
.Execute
Do Until Not .Found
countOccurrences = countOccurrences + 1
.Execute
Loop
End With
rng.Select 'Go back to your place
End Function


2020-12-23 11:13:19

TJ

If I'm looking for how many times a phrase and/or word appears in a document I use the built-in Find and Replace function.

Control-H to open the Find and Replace dialogue box.
Fill in the "Find what" and "Replace" with boxes with the same word/phrase and
Click Replace All

Word executes and displays a pop-up with "All done. We made # of replacements." where # is how many times the word/phrase exists.


2019-05-20 10:32:31

Liz Barron

Hi Allen,

I am trying to write a macro to search through a Word report document and populate the glossary table with any acronyms and definitions that it finds that are in listed in another document that contains a table of acronyms and definitions.

I was wondering if you could give me any advice on how I need to structure this? I'm not looking for you to write the code for me, just point me in the direction I need to be looking at!

I know how to do a find and replace and I know how to write to a table using VBA.

Is there a way to loop through the acronym table document while you are searching, or do I need to put every acronym and definition into the code itself as its own individual find and write to table cell (there are currently about 80 items in the list so this would be a bit of a task!)

I was ideally hoping to come up with a solution that would allow people to add acronyms to the definition table without having to change the code (for instance if there were specific acronyms for certain projects).

Thanks for any help!

Liz


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.