Advanced Scenarios

This chapter has so far discussed a common scenario in which you update your custom command bar controls based on the current selection. Because it depends on what is selected and the current view, the state of the command bars is updated constantly in each of the Office applications. With the combination of the selection change and window activate events, you can mimic the behavior of built-in command bar controls with your own control customizations.

Tracking Documents and Active Windows Using a Custom Window Menu

The Window menu contains a list of active document windows; this not only allows the user to switch between document windows, but also shows which window is the active one. A combination of events is used to update the Window menu in Word, Excel, and PowerPoint.

On the CD-ROM version of this book, the file WndMenu2.xls shows how you can use a combination of events such as window activate, window deactivate, and command bar control clicks to build your own custom window menu. Open the WndMenu2.xls file in Excel and click ALT+F11 to display the Visual Basic for Applications project for this workbook.

When the workbook WndMenu2.xls is opened, the Workbook_Open event procedure in the ThisWorkbook project item of the workbook is executed. The custom Init procedure in the Main code module is called, where the Excel event procedures are set up. The InsertMenu procedure is called from within the Init procedure and it creates the custom window menu called Window2. The InsertMenu procedure also sets up the button Click event for any custom command added to the Window2 menu.

As you open and close workbooks, each workbook's name is either added to or removed from the Window2 menu. When each window is activated, a check mark appears in the Window and Window2 menu adjacent to the name of the workbook that is then active. The WindowActivate and WindowDeactivate events in Excel update where the check mark appears in the custom Window2 menu.

Finally, when a custom command is clicked on the Window2 menu, the button Click event procedure within the CmdBarEvents event class is called. The event procedure determines which workbook should be activated and adds a check mark on the custom command that was clicked. When the workbook is closed, the Workbook_BeforeClose procedure in the ThisWorkbook class module is called. In this procedure, the Uninit procedure in the Main code module is called and the Window2 menu is deleted. The lists in the built-in Window menu and the custom Window2 menu will look identical, as the following figures reveal.

Click to view at full size.

Click to view at full size.