Welcome toWord.Tips.Net
Ask a Word Question
Make a Comment
Learn Access Now
Free Printable Forms
Beauty Tips
Car Tips
Cleaning Tips
College Tips
Cooking Tips
Excel2007 Tips
ExcelTips
Family Tips
Gardening Tips
Health Tips
Home Tips
Legal Tips
Money Tips
Organizing Tips
Pest Tips
Pet Tips
Wedding Tips
Word2007 Tips
WordTips
Setting Fraction Bar Overhang Spacing in the Equation Editor
Printing On Both Sides of the Paper
Turning Off AutoComplete for Dates
Understanding Auto Line Spacing
Adding Comments to Your Document
Conditional Calculations in Word
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
Save Time! WordTips has been published weekly since early 1997. Past issues are available in convenient WordTips archives. Have your own enhanced archive of WordTips at your fingertips, available to use at any time!