Resting Anchor

The Anchorage

Personal website of Gregory K. Maxey, Commander USN (Retired)

Count Occurrences of Selected Text
(A Microsoft Word Help & Tip page by Gregory K. Maxey)

DISCLAIMER/TERMS OF USE

The information, illustrations and code contained in my "Microsoft Word Tips" are provided free and without risk or obligation.

Click to acces PayPal Verification Service Click to acces PayPal Verification Service

However, the work is mine. If you use it for commercial purposes or benefit from my efforts through income earned or time saved then a donation, however small, will help to ensure the continued availability of this resource.

If you would like to donate, please use the appropriate donate button to access PayPal. Thank you!


This Microsoft Word Tips & Microsoft Word Help page introduces and publishes a VBA procedure which provides a fast and simple means to count the number of times a selected word or phrase occurs in your document.

count occurrences 1

While I've include the procedure below, you can download a .dot template file that includes the code and a simple user interface: Count Occurrences.

The template includes a single command button interface control as shown below.

count occurences 2
Word 2003

count occurences 3
Word 2007/2010

Site Note IconNote: Custom menus and toolbars created in Word 2003 templates or documents automatically propagate to the Add-Ins tab in Word 2007/2010.

VBA Script:
Sub TextCountQuick()
'Counts current word or selected word/string.
Dim rngStory As Range
Dim strPhrase As String
Dim i As Long
Dim oShp As Word.Shape
  System.Cursor = wdCursorWait
  'If there is no selection, select current word.
  With Selection
    If .Type <> wdSelectionNormal Then Selection.Words(1).Select
    'Unselect any empty space, line breaks and paragraph marks after text.
    .MoveEndWhile cset:=" ", Count:=wdBackward
    .MoveEndWhile cset:=Chr(13), Count:=wdBackward
    .MoveEndWhile cset:=Chr(11), Count:=wdBackward
     strPhrase = .Text
  End With
  'Reset F/R parameters
  With ActiveDocument.Range.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = ""
    .Replacement.Text = ""
    .Forward = True
    .MatchWholeWord = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Wrap = wdFindStop
  End With
  'Find and count.
  For Each rngStory In ActiveDocument.StoryRanges
    'Iterate through all linked stories
    Do
      With rngStory.Find
        .Text = strPhrase
        Do While .Execute
          i = i + 1
        Loop
      End With
      Select Case rngStory.StoryType
        Case 6, 7, 8, 9, 10, 11
          On Error GoTo Err_Handler
          If rngStory.ShapeRange.Count > 0 Then
            For Each oShp In rngStory.ShapeRange
              If oShp.TextFrame.HasText Then
                With oShp.TextFrame.TextRange.Find
                  .Text = strPhrase
                  Do While .Execute
                    i = i + 1
                  Loop
                End With
              End If
            Next
          End If

        Case Else
          'Do Nothing
      End Select
Err_ReEntry:
      On Error GoTo 0
      'Get next linked story (if any)
      Set rngStory = rngStory.NextStoryRange
    Loop Until rngStory Is Nothing
  Next
  If strPhrase = Chr(13) Then strPhrase = "The paragraph mark"
  If strPhrase = Chr(11) Then strPhrase = "The linebreak"
  If strPhrase = Chr(9) Then strPhrase = "The tab character"
  Select Case i
    Case 1
      MsgBox """" & strPhrase & """ occurs " & i & " time in the document.", , "Text Count"
    Case Is > 1
       MsgBox """" & strPhrase & """ occurs " & i & " times in the document", , "Text Count"
  End Select
  System.Cursor = wdCursorNormal
Exit Sub
Err_Handler:
Resume Err_ReEntry:
End Sub

Additional content.

Site Note icon See: Installing Macros for instructions on how to set up and use the macros provided in this Microsoft Word Help & Microsoft Word Tips page.

That's it! I hope you have found this tips page useful and informative.

Share

PAYMENTS/DONATIONS

Click to acces PayPal Verification Service Click to acces PayPal Verification Service

Do you want to make a payment for consulting work or donate to help support this site?

PayPal is a safe, easy way to pay online.

Use the appropriate currency "Donate" button to make a payment or donation.


Search my site or the web using Google Search Engine

Google Search Logo