Please Note: This article is written for users of the following Microsoft Word versions: 2007 and 2010. 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: Occurrences of a Text String within a Document.

Occurrences of a Text String within a Document

by Allen Wyatt
(last updated June 6, 2017)

6

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

WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (11941) applies to Microsoft Word 2007 and 2010. You can find a version of this tip for the older menu interface of Word 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

Text Prints as Bold, but Displays as Regular

What to do when text looks one way on the screen but prints a different way? This tip provides several different approaches ...

Discover More

Leading Quote Mark Generates Grammar Error

One of the mostly helpful tools that Word includes is a grammar checker. Sometimes, however, the grammar checker might flag ...

Discover More

Using a Filtered Value in a Formula

Accessing filtering criteria for use in a formula can be a real need for some worksheet designs. Getting to that information ...

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)

Saving in Document Format from a Macro

Saving a document in a different format is easy if you are manually using the Save As command. Saving a document in an ...

Discover More

Removing Shortcuts for Macros

Word apparently has a bug in it that makes it very difficult to remove a shortcut key previously associated with a macro. ...

Discover More

Converting Strings to Numbers

When creating macros, you often need to convert a text string that contains numbers into actual numeric values. You do this ...

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 8Mpixels. 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 7 - 2?

2017-06-24 20:05:24

Isabel Leonard

There's an easier way to count occurrences of a text string within a document. 1) Copy the document. The new doc will be temporary. 2) Replace the text string by any character, such as @. Word will tell you how many times this was done. 3) Delete the temporary document.


2017-06-07 01:33:30

C S Petherick

Thanks for your daily nugget - a wonderful service.
But today ('Occurrences of a text string'), I wonder if I've misunderstood something.
Because if I want to check how many occurrences of, eg, Jones, Jones & Co I've got in a text, I turn off Tracking, put Jones, Jones & Co into both the search and the replace boxes, and hit Replace all.
This then tells me the number of times Jones, Jones & Co was replaced.
And I turn Tracking back on again (if it was off in the first place).
What I'm uncertain about, though, is whether a phrase like Jones, Jones & Co counts as a Text String ... ?


2014-04-20 05:33:06

Surendera M. Bhanot

Tough at times there is no solution without Macros and Macros work fine at other instances. Macros are not universal in nature and cannot be employed in all the cases.

In-build capabilities of the application are rather more effective and universal. I void macros and rely more on in-build capabilities. Thanks to Mabel for one such capability of word.


2014-04-20 00:19:23

sarma

This is a good macro I was looking for.
Instead of entering required text string in the inputbox, please suggest a way so that the macro picks up a selected string automatically and counts the occurrences.
I tried but failed to set the selection to a variable.
Regards,
Sarma


2012-07-23 13:25:01

Mark Gordon

I created a document using
=rand(10)
ran the code above with the inputs Insert and Inserted and the results incorrectly reported 9 instances instead of 8
looking at the document the first paragraph now read
"On the Inserteded tab, the"
The macro found the first word twice.
Users have to be careful with what they select as the replace text
repeating the steps but uing "zzzz" (or something that is not already in the document) as the replacement text yielded the correct results


2012-07-23 10:56:22

mabel

There's also a non-macro way of counting the instances of a given string: Go to Home > Find > Advanced Find > In the "Find what" box, white your string, click on the "Reading Highlight" button and in the drop-down select "Hightlight All". This will display in the same dialog box the number of times the string appears in your document and hightlight where it appears in the document.


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.