Ezor
Ezor

Reputation: 145

Count replacements made by "Replace All" in VBA

I'm working on a macro that parses a document and modifies style when needed. So far, one of my sub uses Find & Execute with a loop to go through all paragraph with a defined Style. It worked well enough and made it easy to know how many times modifications have been made. However, it appears that .Execute Replace:=wdReplaceAll is far more efficient, but doesn't return this latter information in VBA, even though it is displayed when used directly in Word (with Ctrl + H).

How can I bypass this issue to count the number of replacements?

Thanks a lot in advance.

Upvotes: 0

Views: 2162

Answers (2)

macropod
macropod

Reputation: 13515

Try something based on:

Sub Demo()
Application.ScreenUpdating = False
Dim i As Long
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = InputBox("What is the Text to Find")
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Execute
  End With
  Do While .Find.Found
    i = i + 1
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
Application.ScreenUpdating = True
MsgBox i & " instances found."
End Sub

The above code doesn't actually replace anything - it simply counts the instances of what's found.

Upvotes: 0

freeflow
freeflow

Reputation: 4355

You could do this with a combination of Word's built in find and replace and a search and replace using the regex library (Microsoft VBScript Regular Expressions 5.5).

The VBScript regular expressions cannot search for styles, only text but can provide the number of matches found.

Thus you first do a search and replace for the paragraph marker of the style in which you are interested (^p + style). You replace the paragraph marker with an amended paragraph marker such as '###^p' being careful to replace with the same style.

You then use the regex search and replace to find the paragraph marker modifier and replace it with nothing, thus restoring the original text. The regex has a method .Matches.Count which will give you the number of replacements of ### that were made.

You may find the following stack overflow link of help

How to Use/Enable (RegExp object) Regular Expression using VBA (MACRO) in word

Upvotes: 1

Related Questions