Executing Sub Procedures

In this section, I describe the various ways to execute, or call, a VBA Sub procedure:

■ With the Run Sub/UserForm command (in the VBE). Or you can press the F5 shortcut key or use the Run Sub/UserForm button on the Standard toolbar.

■ From Excel's Macro dialog box.

■ By using the Ctrl key shortcut assigned to the procedure (assuming that you assigned one).

■ By clicking a button or a shape on a worksheet. The button or shape must have the procedure assigned to it.

■ From another procedure that you write. Sub and Function procedures can execute other procedures.

■ From a custom control in the Ribbon. In addition, built-in Ribbon controls can be "repurposed" to execute a macro.

■ From a customized shortcut menu.

■ When an event occurs. These events include opening the workbook, saving the workbook, closing the workbook, changing a cell's value, activating a sheet, and many other things.

■ From the Immediate window in the VBE. Just type the name of the procedure, including any arguments that may apply, and press Enter.

I discuss these methods of executing procedures in the following sections.

Note In many cases, a procedure will not work properly unless it is executed in the appropriate context. For example, if a procedure is designed to work with the active worksheet, it will fail if a chart sheet is active. A good procedure incorporates code that checks for the appropriate context and exits gracefully if it can't proceed.

0 0

Post a comment