vbams-word

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.


Solution

  • 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