
Tips.Net > WordTips Home > Macros > Occurrences of a Text String within a Document
Summary: You may have a need to find out how many times a certain text string occurs within a document. You can find out manually using the Find and Replace features of Word, but that won’t work in a macro. The technique in this tip will work, however. (This tip works with Microsoft Word 97, Word 2000, Word 2002, Word 2003, and Word 2007.)
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
Tip #3368 applies to Microsoft Word versions: 97 2000 2002 2003 2007
Take Control! Master the real power behind Word! Successfully master the secrets of powerful formatting and create documents that stand out from the rest. Best of all, you can create documents that are easy to maintain and quick to change.
Check out WordTips: Styles and Templates today!
The real power behind Word's best documents lies in understanding styles and templates. Learn the key to more powerful document creation. (more information...)
Ask a Word Question
Make a Comment
Beauty Tips
Car Tips
Cleaning Tips
College Tips
Cooking Tips
Excel2007 Tips
ExcelTips
Family Tips
Gardening Tips
Health Tips
Home Tips
Money Tips
Organizing Tips
Pest Tips
Pet Tips
Word2007 Tips
WordTips