How to Write Document Cleanup Macros in Word 2016

By Dan Gookin

Before that final save, or any time you’re working on a large document in Word 2016, consider doing some document cleanup. It’s a process that involves searching for rogue characters and other problematic text.

A document cleanup routine involves looking for trailing spaces at the end of paragraphs, double spaces, double tabs, and double Enter keys (empty paragraphs). These are all items to be avoided, but they end up in long documents anyway.

The process of eliminating these unwanted elements involves using the Find and Replace dialog box. You need to use the Special button to input special characters, such as Space, Tab, and Enter.

The macro created to perform the document cleanup chore recorded the keystrokes used to search and replace for the various characters. Then the Visual Basic Editor was used to remove some of the redundant code. Here is the result:

Sub document_cleanup()

'

' document_cleanup Macro

' Remove trailing spaces and double spaces, tabs, and Enter keys

'

Selection.HomeKey Unit:=wdStory

Selection.Find.ClearFormatting

Selection.Find.Replacement.ClearFormatting

' Remove trailing spaces from a paragraph

With Selection.Find

.Text = "^w^v"

.Replacement.Text = "^v"

.Forward = True

End With

Selection.Find.Execute Replace:=wdReplaceAll

' Remove double spaces

With Selection.Find

>.Text = " "

.Replacement.Text = " "

End With

Selection.Find.Execute Replace:=wdReplaceAll

' Remove double tabs

With Selection.Find

.Text = "^t^t"

.Replacement.Text = " ^t"

End With

Selection.Find.Execute Replace:=wdReplaceAll

' Remove double Enter keys (blank paragraphs)

With Selection.Find

.Text = "^v^v"

.Replacement.Text = "^v"

End With

Selection.Find.Execute Replace:=wdReplaceAll

End Sub

The first search-and-replace operation removes trailing spaces. The search text is ^w^v, which looks for any white space (^w) characters before the Enter key (^v). These whitespace characters — space, tab, and so on — are replaced with the Enter key, which removes the trailing spaces.

The second search-and-replace removes double spaces. press the spacebar twice for the search text and pressed the spacebar a single time for the replacement text.

The third search-and-replace removes double tabs. The ^t represents tab characters in the Find and Replace dialog box.

The final search-and-replace removes empty paragraphs. The ^v characters represent the Enter key, so replacing ^v^v with ^v removes any empty paragraphs.

This macro works okay, but it could be better. For example, it doesn’t handle triple spaces or triple tabs. You’d have to run the macro a second time for that. If you provide the programming talent, the macro’s code can address those issues.