Customizing Word 2003

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

Summary: Review options for customizing Microsoft Office Word 2003 including customization scopes, storage, and considerations for design-time customizations versus run-time customizations. (17 printed pages)

Bill Coan, Microsoft Word MVP

September 2006

Applies to: Microsoft Office Word 2003

Contents

  • Overview

  • Customization Scope

  • Conflicting Customizations

  • Limiting Customization Scope to What Is Actually Required

  • Design-Time Customizations vs. Run-Time Customizations

  • Design-Time Customizations of Menus, Toolbars, and Keyboard

  • A Word of Caution About Design-Time Customizations

  • Run-Time Customizations of Menus, Toolbars, and Keyboard

  • A Word of Caution About Run-Time Customizations

  • First, Do No Harm

  • About the Author

  • Additional Resources

Overview

You can customize Microsoft Office Word 2003 in a variety of ways to optimize for almost any word-processing need. When I say that you can customize Word, I do not mean changing the definitions of paragraph styles (or other styles) in a template. Nor am I talking about storing elements of content as AutoText entries or creating AutoCorrect entries. These things can have a tremendous impact on a user's productivity, and they can change a user's experience of Word, but they don't change the way Word itself works. They are expressions of built-in Word capabilities. Customizations go beyond built-in capabilities, actually changing the way Word works.

Customizations can include any combination of the following:

  • Event handlers that alter the way Word responds to the opening or closing of a document, the changing of the selection within a document, or a variety of other events. Because event handlers are triggered automatically by the events they handle, the user need not take any explicit action to invoke them. For more information about event handlers, see Take Control of Microsoft Word Through Events.

  • Macros that run in place of (and can alter the operation of) built-in commands in Word. You can invoke such macros by using built-in menus, toolbars, or keystrokes that otherwise invoke built-in Word commands.

  • Macros that perform specialized operations beyond those possible or convenient with built-in commands in Word. You can invoke such macros by using custom menus, toolbars, or keystrokes.

  • Menu, toolbar, and keyboard customizations that control how macros and built-in commands in Word are invoked by a user.

You can store customizations in any combination of the following locations:

  • The active document

  • The template attached to the active document

  • A global template or add-in template

  • The default global template (Normal.dot)

  • A Component Object Model (COM) add-in, also known as a dynamic-link library (DLL) add-in

To create a COM add-in, you must have access to a development tool capable of creating .dll files, such as the tools available in Microsoft Visual Studio 2005 and Microsoft Visual Studio .NET.

Although you can generate menu, toolbar, and keyboard customizations by code stored in any of these locations, you can permanently store the customizations themselves only in the first four locations. Because COM add-ins cannot store customizations, you must exercise special care when choosing where to permanently store customizations generated by a COM add-in. Otherwise, the customizations could have more scope or less scope than intended, with serious consequences for the user. For more information, see the Customization Scope and Design-Time Customizations vs. Run-Time Customizations sections of this article.

Customization Scope

This section reviews the different locations in which you can store customizations. Each location has its own advantages and disadvantages.

Storing Customizations in the Active Document

Customizations stored in the active document take effect as soon as the document becomes active and remain in effect only so long as the document remains active. You should choose the location most appropriate to your customization but that limits the scope to the minimum required level.

Storing Customizations in the Template Attached to the Active Document

Customizations stored in the template attached to the active document take effect as soon as the document becomes active or as soon as it becomes attached to the template (whichever is later) and remain in effect only so long as the document remains active and attached to that template. If the document is detached from the original template and attached to some other template, or if the document loses focus to another document that is attached to some other template, the customizations in the original template cease to be in effect and are replaced by the customizations (if any) stored in the other template.

Storing Customizations in a .dot Add-in File

Customizations stored in a .dot add-in file take effect as soon as the add-in file is loaded into the Word memory space and remain in effect until the add-in file is unloaded from the Word memory space.

A .dot add-in file stored in the Word Startup folder or the Microsoft Office Startup folder automatically loads into the Word memory space when Word starts, and then unloads when Word closes. Therefore, the customizations stored in such a file are in effect throughout the entirety of every Word session for as long as the add-in file remains stored in the Startup folder (unless the user explicitly unloads the add-in file at some point).

Regardless of where it is stored, you can manually load and unload a .dot add-in file to the Word memory space by user action, from code run from a template, or from another .dot add-in or a COM add-in.

To load a .dot add-in file into the Word memory space manually, on the Tools menu, click Templates and Add-Ins and then select the check box for the add-in you want. If that add-in you want is not listed, click Add… and browse to the add-in. To manually unload an add-in file from the Word memory space, on the Tools menu, click Templates and Add-Ins and then clear the check box for the add-in.

Storing Customizations in the Default Global Template (Normal.dot)

Customizations stored in the Word default global template (Normal.dot) automatically load into the Word memory space when Word starts and unload when Word closes. Therefore, any customizations stored in this template are in effect throughout every Word session.

Storing Customizations in a COM Add-in File

Customizations stored in a COM add-in file take effect as soon as the add-in file loads into the Word memory space and remain in effect until the add-in file unloads from the Word memory space.

Customizations stored in a COM add-in file and registered as an autoloading add-in for Word load automatically into the memory space when Word starts and unload when Word closes. Therefore, the customizations stored in such a file are in effect throughout every Word session for as long as the add-in file remains registered.

Remember that, in the Microsoft Windows registry, COM add-in files for Word are listed in the following locations:

  • HKEY_CURRENT_USER\Software\Microsoft\Office\Word\Addins\ProgID\LoadBehavior

  • HKEY_LOCAL_MACHINE\Software\Microsoft\Office\Word\Addins\ProgID\LoadBehavior

Files listed under HKEY_CURRENT_USER can be loaded only by the current user. Files listed under HKEY_LOCAL_MACHINE can be loaded by any user. The LoadBehavior value reveals whether the file is currently loaded and also determines when the file loads.

  • 0 = Disconnected. File is not loaded.

  • 1 = Connected. File is loaded.

  • 2 = Bootload. Load file on application startup.

  • 8 = Demand Load. Load file only when requested by user.

  • 16 = Connect First Time. Load file only once (on next startup).

For example, a value of 3 indicates that the add-in file is currently loaded and that it loads on application startup (1 + 2 = 3). A value of 9 indicates that the add-in file is currently loaded and that it loads only when requested by the user (1 + 8 = 9).

Users can also manually load and unload customizations stored in a COM add-in file and registered under HKEY_CURRENT_USER. The command for loading and unloading such add-ins does not appear on Word menus by default, but you can add it to the Tools menu by doing the following:

  1. Start Word.

  2. On the Tools menu, click Customize.

  3. Click the Commands tab.

  4. In the Categories list, click Tools.

  5. In the Commands list, click COM Add-Ins and drag it to the Tools menu.

  6. Wait for the menu to display.

  7. Position the cursor just below the Templates and Add-ins command, and then release the mouse.

To load a .dll add-in file into the Word memory space manually, on the Tools menu, click COM Add-ins and then select the check box for the add-in you want. If the add-in you want is not listed, click Add… and browse to the add-in. To manually unload an add-in file from the Word memory space, on the Tools menu, click COM Add-Ins and then clear the check box for the add-in.

Note

You cannot have users manually load and unload in the Word memory space customizations that are stored in a COM add-in file and registered under HKEY_LOCAL_MACHINE because they do not show up in the COM Add-ins dialog box.

Conflicting Customizations

Because you can store customizations in multiple locations and the scope of customizations in one location can overlap the scope of those in another location, conflicts can arise. To resolve such conflicts, Word assigns precedence to customizations according to the following locations:

  1. The active document. Customizations stored in the active document take precedence over any other customizations that are present.

  2. The template attached to the active document. Customizations stored in the template attached to the active document take precedence over customizations stored in add-in files or in the default global template (Normal.dot).

  3. Add-in files, in order of loading. The most recently loaded add-in file takes precedence over add-in files loaded earlier.

    Note

    Because you can load add-in files automatically from the Word Startup folder, or from the Microsoft Office Startup folder, and manually from any location at any time, there is no way to determine that your file will load before or after any other particular add-in file.

  4. The default global template (Normal.dot). Customizations stored in the default global template are loaded first, which means that customizations stored in all other locations can overwrite them.

Limiting Customization Scope to What Is Actually Required

Although customizations can help users to be more productive, even well-thought-out customizations have the potential to interfere with the user's productivity in unexpected ways. Therefore, the most important rule when customizing Word is to limit the scope of customizations to what is actually required.

Scope: Document. If the goal of the customizations is to help the user work with a particular document, then you should store the customizations in that document. This ensures that the customizations are present only when that document is being worked on.

Note

Keyboard customizations stored in a document are more fragile than other customizations, and they can disappear if the user switches to a different document and then switches back to the document containing the customizations. For this reason, you should not store keyboard customizations in a document if the user is likely to switch temporarily to a different document and then return to the original document.

Scope: Class of documents. If the goal of the customizations is to help the user work with an entire class of documents, then you should create a custom template and attach all the documents to it. Then, you can store the customizations in that template. This ensures that the customizations are present only when documents attached to that template are being modified.

Scope: All documents. If the goal of the customizations is to help the user perform a particular task regardless of which document (or class of documents) is being worked on, then, by necessity, you must store the customizations in an add-in file.

Scope: Infrequent or predictable. If the user performs a particular set of tasks infrequently or at very predictable times, then you should load the add-in file that stores the customizations for that set of tasks into the Word memory space only when needed. It should be unloaded when no longer needed. This ensures that the customizations are present when needed but only when needed.

Scope: Frequent or unpredictable. If the user performs a particular set of tasks frequently or at unpredictable times, then you might choose to keep the add-in file that stores the customizations for that set of tasks in the Word Startup folder or in the Microsoft Office Startup folder. In the case of a COM add-in, you might choose to register it as an autoloading file, so that it loads into the memory space when Word starts and remains there until the user exits Word or explicitly unloads it. This ensures that the customizations are present throughout every Word session.

It is almost never a good idea for a developer to store customizations in Normal.dot, for the following reasons:

  • Normal.dot is the default location for user customizations. Users who know very little about Word can quickly accumulate various customizations of great value to them in Normal.dot. Any interference with these customizations by a developer will be viewed (rightfully) as an intrusion on the user's workspace.

  • Normal.dot can become corrupt. When corrupt, it must be deleted so that Word can generate a fresh copy. When this happens, any customizations stored in Normal.dot by a developer are lost.

  • In some corporate environments, Normal.dot is overwritten daily by a network logon policy. In addition to being an aggravation to users, this practice interferes with a developer's efforts to store customizations in Normal.dot.

Design-Time Customizations vs. Run-Time Customizations

When a developer stores customizations in a file before the file is distributed to the user, the customizations are referred to as design-time customizations. When a user receives a file from a developer and the file triggers customizations while Word is running under user control, the customizations are referred to as run-time customizations.

Event Handlers and Macros

Most event handlers and macros are written at design time. Although you can automate the Microsoft Visual Basic for Applications Integrated Development Environment (VBE IDE) to produce event handlers and macros at run time, such automation is not required very often and is outside the scope of this article.

If you write an event handler or a macro at design time and save the code in a .doc file, a .dot file, or a .dll file, there is no ambiguity about where to store the macro or event handler or about its scope. It is stored in the file that you choose, and its scope is dictated by when the file is loaded into the Word memory space, by when the file is unloaded from the memory space, and by the rules of precedence regarding conflicts among customizations.

You can usually handle customizations to menus, toolbars, and the keyboard in Word the same way you handle most macros and event handlers. That is, you create the customizations at design time and save them in a .doc or .dot file. Thereafter, the scope of the customizations is dictated by when the file is loaded into the Word memory space, by when the file is unloaded from the memory space, and by the rules of precedence regarding conflicts among customizations.

In the case of COM add-ins, it is not possible to create customizations of Word menus, toolbars, or the keyboard at design time, because COM add-in files have no way to store such customizations. The most that a COM add-in can do is to store at design time the code needed to carry out the customizations at run time.

In some cases, the exact nature of customizations needed (whether of the menus, toolbars, or keyboard) might not be knowable until run time. In such cases, the developer has no choice but to consider run-time customizations.

Design-Time Customizations of Menus, Toolbars, and Keyboard

When creating menu, toolbar, and keyboard customizations in a .doc or .dot file at design time, the developer has two options: create the customizations by using the Word user interface (UI) or create them using macro code.

To create design-time customizations from the UI, on the Tools menu, click Customize and then click Keyboard. The dialog boxes that appear enable you to create the customizations and to select the file in which to store the customizations, such as the active document, its attached template, the active template (if the active document is a template), or the default global template (Normal.dot). You can then save that file as usual. Thereafter, the scope of the customizations is dictated by when the file is loaded into the Word memory space, by when it is unloaded from the memory space, and by the rules of precedence regarding conflicts among customizations.

To create design-time customizations by using macro code, you write and then run a macro, such as the following.

[VBA]
Option Explicit
Sub CustomizeWord()
'**********************************************************************
'**********************************************************************
'**********************************************************************
'This macro customizes the Word UI by assigning a macro called
'"TemplateVersion" to run when the user presses F10. This macro also creates
'a custom toolbar and then places a control button on that toolbar and sets
'the button's "OnAction" property to the TemplateVersion macro.
'Note that the TemplateVersion macro is listed below, immediately after the code
'for the CustomizeWord macro.
'**********************************************************************
'**********************************************************************
'**********************************************************************
'Declare some variables for a custom toolbar:
   Dim oCB As CommandBar
   Dim oControl As CommandBarButton
   'Set the customization context in such a way that the
   'customizations are stored in the same file as this code.
   CustomizationContext = ThisDocument
   'Clear any keyboard customizations left by previous
   'executions of this macro:
   KeyBindings.ClearAll
   'Assign the F10 key to the "TemplateVersion"
   'macro stored in the modCustomization module of the
   'WordCustomizationProject.
   KeyBindings.Add _
      KeyCode:=BuildKeyCode(wdKeyF10), _
      KeyCategory:=wdKeyCategoryMacro, _
      Command:="WordCustomizationProject.modCustomization.TemplateVersion"
   'Note that "WordCustomizationProject.modCustomization.TemplateVersion"
   '(see previous) is a fully qualified macro name.
   'Using the fully qualified name helps ensure
   'that Word runs the proper macro. If there are two or more
   '"TemplateVersion" macros, Word runs only the
   'one stored in the modCustomization module of the
   'project called WordCustomizationProject. (You can change project 
   'names and module names in the Properties pane of the VBA IDE.)
   'Important: Always assign unique names to your code projects and 
   'code modules, so that Word can determine
   'exactly which macro you want to run.
   'Delete the existing Custom Toolbar, if present.
   'Ignore errors, in case the toolbar does not yet exist.
   On Error Resume Next
   CommandBars("Custom Toolbar").Protection = msoBarNoProtection
   CommandBars("Custom Toolbar").Delete
   On Error GoTo 0
   'Create a command bar called Custom Toolbar.
   Set oCB = _
   CommandBars.Add( _
            Name:="Custom Toolbar", _
            Position:=msoBarFloating)
   'Set the new command bar to be visible and position it, for now,
   '100 pixels from the left edge and 200 pixels from the
   'top edge of the Word application window.
   With oCB
      .Visible = True
      .Left = 100
      .Top = 200
   End With
   'Add a control button to the new command bar:
   Set oControl = oCB.Controls.Add(Type:=msoControlButton)
   'Set the control button to display its caption,
   'then set its caption to "Version" and
   'set the button's "OnAction" property to the "TemplateVersion"
   'macro stored in the modCustomization module.
   With oControl
      .Style = msoButtonCaption
      .Caption = "Version"
      .OnAction = "modCustomization.TemplateVersion"
   End With
   'Note that "modCustomization.TemplateVersion" (see previous) is NOT 
   'a fully qualified macro name, but it is the closest we 
   'can come to one.
   'Ideally, we would include the project name ("WordCustomizationProject")
   'when specifying which macro we want Word to run, but unfortunately
   'there is a bug in the OnAction property that prevents this. 
   'The best we can do is to include
   'the module name along with the macro name, to help
   'distinguish the desired macro from an identically named macro
   'in some other module.
   '(Module names can be changed in the
   'Properties pane of the VBA IDE.)
   'Important: Always assign unique names to your code modules,
   'so that Word can determine exactly which macro you want to run.
   'Protect the custom command bar to ensure it stays visible and
   'also to ensure that it is not further customized by the user.
   With oCB
      .Protection = msoBarNoChangeVisible + msoBarNoCustomize
   End With
   'Release variables from memory
   Set oCB = Nothing
   Set oControl = Nothing
   'Force the customization context to return to the active document's
   'attached template, or to Normal.dot if no document is open.
   'This helps ensure that Word continues to display
   'all current customizations.
   If Documents.Count > 0 Then
      CustomizationContext = ActiveDocument.AttachedTemplate
   Else
      CustomizationContext = NormalTemplate
   End If
End Sub

Sub TemplateVersion()
   MsgBox "Word Customization Code" & vbCr & _
            "Version 1.0"
End Sub

Notice that the macro sets the customization context before implementing its customizations. The customization context specifies where to store the customizations. In the macro, the customization context is set to ThisDocument, which refers to the file where the macro code itself is stored.

Also notice that the code explicitly resets any earlier customizations stored in the same customization context. This helps prevent successive customizations from piling up on top of one other, which could, for example, cause a new toolbar to appear alongside older toolbars created during previous executions of the code.

Note

Resetting earlier customizations does not reduce the file size of .doc and .dot files. On the contrary, all customizations and resets tend to increase the file size. The problem seems to be that Word does not actually delete the old customizations, but allows them to accumulate within the file even though they are not used. For more information, see "Invalid Page Fault" Message when Running a Macro.

Other possible customization contexts include:

  • ActiveDocument

  • ActiveDocument.AttachedTemplate

  • Templates (filespec for a currently loaded add-in template)

  • NormalTemplate

    Important

    Setting the customization context to NormalTemplate (the default global template) pollutes the Normal template and causes Word to save changes to the Normal template without prompting the user, or else to prompt the user to save the changes depending on whether the user has chosen to be prompted before saving the Normal Template. As a general rule, this is a very bad programming practice. The default global template, Normal.dot, is the user's file and should not be changed by anyone other than the user. Also, because Normal.dot is sometimes overwritten during network logon, and because many users delete Normal.dot when troubleshooting a problem with Word, customizations stored in Normal.dot can be lost unexpectedly. For more information about add-ins and Normal.dot, see Word Prompts Me to Save Changes to the Normal.dot Template.

Finally, notice that the code explicitly sets the customization context to a known value after the customizations are completed. This is a good practice, especially for code that might one day be used at run time rather than design time. If the customization context is set at the start of the macro to, for example, an add-in template, the Word UI might temporarily reflect only the customizations stored in that template, rather than continuing to reflect other current customizations. By explicitly setting the customization context to a known value after completion, you can help ensure that the Word UI immediately reflects all customizations of interest to the user.

Note

In most cases, a customization macro should end by setting the customization context to the active document's attached template or to the default global template, Normal.dot. The most notable exception occurs when the customization macro is storing customizations in the active document. In that case, the customization context should remain set to the active document, because setting it to some other value hides any toolbars added to the active document, defeating the purpose of the customization code.

After the example macro executes and the customizations are created, you can save the file where the customizations are stored, as usual. Thereafter, the scope of the customizations is dictated by when the file is loaded into the Word memory space, by when it is unloaded from the memory space, and by the rules of precedence regarding conflicts among customizations.

A Word of Caution About Design-Time Customizations

For best results, it is important to create design-time customizations on a non-customized instance of Word. That is, no add-ins should be loaded and the default global template (Normal.dot) should be a fresh copy generated by Word containing no modifications by the developer.

Note

To generate a fresh copy of Normal.dot, exit Word and Microsoft Office Outlook, rename all existing instances of Normal.dot to Normal.old, then restart Word.

The reason for this requirement is that customizations can be subtractive or additive. Here is an example of how this can lead to unintended results:

Suppose that an instance of Word is running, that the active document is a .dot file, and that you are creating some customizations using the UI. Further suppose that the DataPrompter add-in (from Coan and Company, Inc.) is loaded into this instance of Word.

In this scenario, on the Tools menu, if you click Customize and remove the Table menu from the Word menu and then remove the DataPrompter menu from the Word menu, the result is subtractive customizations. When the .dot file is distributed to users, the customizations indicate to Word to remove both the Table menu and the DataPrompter menu. Users who have not installed the DataPrompter add-in do not notice the lack of the DataPrompter menu, because they do not expect to see it, but users who have installed the DataPrompter add-in will wonder why the DataPrompter menu has gone missing.

Notice that, in this example, the DataPrompter menu disappears even though no change is made to the DataPrompter add-in itself. The DataPrompter add-in still contains an add-in menu for the menu, just as it always has. The difference is that Word chooses not to display the add-in menu, because the .dot file contains a subtractive customization directing Word to remove it.

This scenario illustrates that no add-in developer can give users a predictable experience if other developers distribute subtractive design-time customizations that override their work. For this reason, all developers should familiarize themselves with the scope of customizations, the rules of precedence that govern conflicts, and the potential for one developer's design-time customizations to interfere with those of another.

The good news is that you can minimize the potential for these problems by ensuring that customizations are carried out on a non-customized instance of Word. In such an instance, customizations from other developers are not present and therefore are not at risk of inadvertent subtraction.

Run-Time Customizations of Menus, Toolbars, and Keyboard

To customize menus, toolbars, and the keyboard at run time, you rely on code created at design time that runs at run time. In most cases, the code can be nearly identical to what you run at design time to accomplish design-time customizations. In fact, in most cases the only real difference, if any, is the customization context.

Because run-time code could be running in the presence of customizations stored in a variety of contexts, it is critical to start by setting the customization context to the desired context (typically ThisDocument) and end by setting the customization context to a known value (typically ActiveDocument.AttachedTemplate or NormalTemplate), unless the customizations are being stored in the active document, in which case the context must remain set to the active document. Otherwise, after the code runs, the Word UI in some cases might temporarily reflect only the latest customizations and fail to continue reflecting other customizations.

In the case of code stored in a COM add-in (a .dll file), you must set the customization context to an appropriate .doc or .dot file, because the .dll file itself cannot store customizations to menus, toolbars, or the keyboard. Many developers of COM add-ins automatically assume that their only choice is to set the run-time customization context to NormalTemplate, which causes the customizations to be stored in Normal.dot. As noted earlier, customizations stored in Normal.dot can interfere with user customizations, and may be lost if Normal.dot becomes corrupt or if a network logon script overwrites it.

For developers who insist on storing their customizations in Normal.dot, it is important to make very precise references to the menus, toolbars, or keybindings being customized, so that the customizations do not affect the user's own customizations or those stored in Normal.dot by some other developer's add-in.

A more conservative approach is to distribute a .dot file along with the COM add-in, and to store all customizations in the .dot file. Most developers store the .dot file in the Word Startup folder or the Microsoft Office startup folder, but it can be stored anywhere. You can store it in a convenient location and load it into Word (as a global template add-in) by using your COM add-in before run-time customizations are carried out.

After customizations are created at run time, you can save the file where the customizations were stored to the same customization context, using one of the following statements:

  • ThisDocument.Save

  • ActiveDocument.Save

  • ActiveDocument.AttachedTemplate.Save

  • Templates(filespec for a currently loaded add-in template).Save

  • NormalTemplate.Save

Alternatively, you can mark the customization context as already saved, so that Word does not attempt to save the associated file upon exit. To do so, use one of the following statements:

  • ThisDocument.Saved = True

  • ActiveDocument.Saved = True

  • ActiveDocument.AttachedTemplate.Saved = True

  • Templates(filespec for a currently loaded add-in template).Saved = True

  • NormalTemplate.Saved = True

    Note

    Setting the Normal template's Saved property to True prevents Word from saving changes to the Normal template (or prompting the user to do so) even if the Normal template contains changes made by the user. As a general rule, this is a very bad programming practice, because changes made by the user can be lost without notice.

A Word of Caution About Run-Time Customizations

Unlike code for design-time customizations, which is usually executed explicitly by the developer, code for run-time customizations is more typically triggered by an event. For example, a COM add-in might rely on its OnLoad event, or a .dot file loaded as a global add-in might rely on an AutoExec macro, to trigger the execution of run-time customizations.

There are two problems with triggering run-time customization code by events.

First, the timing of events is outside of the developer's control (and it is also outside of the user's control). For example, if two different .dot files are stored in the Word Startup folder, and each of them contains an AutoExec macro, it is difficult to predict the order in which they will run.

Second, event code is not necessarily executed all at once. Instead, if multiple events have taken place, or if an event occurs while an OnLoad event handler or AutoExec macro is executing, Word switches back and forth among all of the queued processes and tries to make a little bit of progress on each one before carrying any individual routine to completion.

In some cases, Word can loop through all of the events several times before a particular customization routine is executed to completion. Worse yet, changes in customization context can take place without warning as Word loops through the various events, either because the code in each event handler explicitly sets the customization context to a different value or because Word temporarily switches the customization context as it loads various files into memory. In too many cases, the customization context can be switched so often and so suddenly that a customization intended for one context is instead applied to a different context.

Testing under a variety of conditions (with and without other add-ins present, with and without Outlook running, with and without Outlook using Word as its e-mail editor, with and without other Windows processes running) can help reveal some of the problems that can occur with run-time customizations. Unfortunately, other problems might not show up until after testing is completed and an add-in is released for distribution.

One way to avoid run-time problems is to rely completely on design-time customizations. In the case of a COM add-in, this means preparing and distributing a .dot add-in along with the COM add-in, with customizations stored in the .dot add-in.

You can minimize run-time problems by limiting run-time customizations to those carried out when a user clicks a pop-up control, such as a menu. Similar to other command bar controls, pop-up controls have an OnAction property that enables them to run a macro when clicked.

Because a pop-up control's OnAction macro might run in the presence of customizations stored in a variety of contexts, it is critical that such a macro start by setting the customization context to the desired context (typically ThisDocument) and end by setting the customization context to a known value (ActiveDocument.AttachedTemplate or NormalTemplate), unless the customizations are being stored in the active document, in which case the context must remain set to the active document. If this precaution is neglected, the Word interface might temporarily reflect only the latest customizations and fail to continue reflecting other customizations.

The following macro shows how you can use a pop-up control's OnAction property to configure the menu that pops up when the user clicks the control.

[VBA]
Option Explicit
Sub DynamicallyAdjustMenu()
'**********************************************************************
'**********************************************************************
'**********************************************************************
'This macro customizes the Word UI by enabling or disabling
'the first control found on a pop-up control. Whenever the user clicks 
'the pop-up control, Word evaluates how many documents are open and 
'either enables or disables the first control on the pop-up menu.
'**********************************************************************
'**********************************************************************
'**********************************************************************
'Declare a Boolean variable
'to store the "saved" status of the
'file containing this code.
   Dim blnSaved As Boolean
   'Store the saved status of the file
   'containing this code.
   blnSaved = ThisDocument.Saved
   'Set the customization context in such a way that the
   'customizations are stored in the same file as this code.
   CustomizationContext = ThisDocument
   'If more than one document is open,
   'enable the first control on the menu
   'that called this routine. Otherwise
   'disable the first control on the menu.
   With CommandBars.ActionControl
      If Documents.Count > 1 Then
      .Controls(1).Enabled = True
      Else
      .Controls(1).Enabled = False
      End If
   End With
   'Because the previous customization pollutes
   'the file containing this code,
   'set the file's Saved bit to what it was
   'before the customization was made.
   'This prevents Word from prompting the
   'user to save the file.
   ThisDocument.Saved = blnSaved
   'Force the customization context to return to the active document's
   'attached template, or to Normal.dot if no document is open.
   'This helps ensure that Word continues to display
   'all current customizations.
   If Documents.Count > 0 Then
      CustomizationContext = ActiveDocument.AttachedTemplate
   Else
      CustomizationContext = NormalTemplate
   End If
End Sub

First, Do No Harm

Customizing Word can be as simple as writing a single macro or event handler or as complicated as you desire. No matter how modest or ambitious the project, as a responsible developer, you must start by confronting the issues of storage location and scope and the potential for conflicts among customizations. You must also consider the question of whether to rely exclusively on design-time customizations or on a mixture of design-time customizations and run-time customizations. Beyond these principles, your primary design goal should be to do no harm to Word itself or to any other templates or add-ins that might be present.

About the Author

Bill Coan is the founder and president of Wordsite Office Automation. He has specialized in document design, automation, and business process improvement since the early 1980s. He is a recognized leader in the development of custom Microsoft Office solutions. For more information, see http://www.wordsite.com.

Additional Resources

For more information, see the following resources: