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

by Allen Wyatt
(last updated February 16, 2019)

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

Easily Adding Blank Rows

Want to add a bunch of blank rows to your data and have those rows interspersed among your existing rows? Here's a quick ...

Discover More

Separating a Date into Component Columns

Do you need a way to split dates out into the individual parts that make up that date? This tip provides two easy ways ...

Discover More

Jumping to the Ends of Table Rows

Need to jump from one end of a table row to another? Word provides a couple of handy shortcuts that can make this type of ...

Discover More

Create Custom Apps with VBA! Discover how to extend the capabilities of Office 2013 (Word, Excel, PowerPoint, Outlook, and Access) with VBA programming, using it for writing macros, automating Office applications, and creating custom applications. Check out Mastering VBA for Office 2013 today!

More WordTips (menu)

Moving the Insertion Point to the Beginning of a Line

If you need to move the insertion point within your macro, then you'll want to note the HomeKey method, described in this ...

Discover More

Setting the Right Indent of a Paragraph in a Macro

Need to format your document using a macro? You can easily set the right margin for an individual paragraph by using the ...

Discover More

Displaying the Document Title Right Away

One of the properties that Word maintains for a document is a title. If you want this title displayed on the title bar ...

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 eight more than 4?

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.