Bulletproofing

Many macros are fragile initially: Everything must be just so, or they won't run properly. Fragile macros are fine if you're the only one who uses them. But if you're writing a macro others might use, you have to consider all the conditions in which someone might run it. Bulletproofing is the process of making a macro less dependent on a particular set of conditions.

The following is a checklist of questions to consider.

Where is the insertion point or selection when the macro begins?

A macro that uses editing statements may not work correctly if the insertion point or selection is in a table or a frame. If the insertion point or selection is in a macro-editing window or a header, footer, footnote, or annotation pane, a macro may not run because many commands are not available. You can use the SelInfo() function to determine whether the insertion point or selection is in a macro-editing window or a pane.

Is there a selection?

Often, macros that are designed to help with editing assume that text is either selected or not selected. A bulletproofed macro would use the SelType() function to test that assumption and quit if the selection were inappropriate.

Which view is the document in?

A macro that runs properly in normal view may not work in outline view or page layout view.

Is a window open?

Most Word commands are unavailable when no document window is open.

What are the current Word settings?

The settings in the Options dialog box (Tools menu) can often determine whether a macro runs properly. For example, a macro that pastes text onto or types over a selection depends on whether the Typing Replaces Selection check box on the Edit tab is selected. If a macro searches for or edits hidden text, hidden text must be visible; however, if a macro repaginates (or compiles an index or table of contents), page numbering may be thrown off if hidden text is visible. Use the WordBasic statements that control the Options dialog box to ensure the current settings are appropriate for your macro.

Could the macro trigger an auto macro?

If the macro performs any of the actions that can trigger an auto macro (such as opening an existing document or creating a new one), it may be disrupted or perform unnecessary actions. You can disable auto macros using the DisableAutoMacros statement.

What if the user interrupts the macro?

Usually, it's convenient to be able to cancel a macro by pressing the Esc key. But if a macro is carrying out a critical operation, canceling it could create problems. You can use the DisableInput statement to prevent the user from canceling a macro.

Bulletproofing and Speed

Every bulletproofing precaution slows your macro down. For long, complex macros, the added robustness is well worth a slight delay at the start. For short, quick macros, however, speed may be critical — if they take too long, they're not worth using. Use your judgment as to what level of bulletproofing is appropriate for a given macro.