18.11.2014 Views

Microsoft Office

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Part VI<br />

Programming Excel with VBA<br />

TABLE 43.1<br />

(continued)<br />

Event<br />

Open<br />

SheetActivate<br />

SheetBeforeDoubleClick<br />

SheetBeforeRightClick<br />

SheetCalculate<br />

SheetChange<br />

SheetDeactivate<br />

SheetFollowHyperlink<br />

SheetSelectionChange<br />

WindowActivate<br />

WindowDeactivate<br />

WindowResize<br />

Action That Triggers the Event<br />

The workbook is opened.<br />

Any sheet in the workbook is activated.<br />

Any worksheet in the workbook is double-clicked. This event occurs before the<br />

default double-click action.<br />

Any worksheet in the workbook is right-clicked. This event occurs before the<br />

default right-click action.<br />

Any worksheet in the workbook is calculated (or recalculated).<br />

Any worksheet in the workbook is changed by the user.<br />

Any sheet in the workbook is deactivated.<br />

Any hyperlink in the workbook is clicked.<br />

The selection on any worksheet in the workbook is changed.<br />

Any window of the workbook is activated.<br />

Any workbook window is deactivated.<br />

Any workbook window is resized.<br />

The remainder of this section presents examples of using workbook-level events. All the example procedures<br />

that follow must be located in the code module for the ThisWorkbook object. If you put them into<br />

any other type of code module, they will not work.<br />

Using the Open event<br />

One of the most common monitored events is a workbook’s Open event. This event is triggered when the<br />

workbook (or add-in) opens and executes the Workbook_Open procedure. A Workbook_Open procedure<br />

is very versatile and is often used for the following tasks:<br />

n<br />

n<br />

n<br />

n<br />

Displaying welcome messages.<br />

Opening other workbooks.<br />

Activating a specific sheet.<br />

Ensuring that certain conditions are met; for example, a workbook may require that a particular<br />

add-in is installed.<br />

Be aware that there is no guarantee that your Workbook_Open procedure will be executed.<br />

For example, the user may choose to disable macros. And if the user holds down the Shift key<br />

while opening a workbook, the workbook’s Workbook_Open procedure will not execute.<br />

CAUTION<br />

The following is a simple example of a Workbook_Open procedure. It uses VBA’s Weekday function to<br />

determine the day of the week. If it’s Friday, a message box appears to remind the user to perform a file<br />

backup. If it’s not Friday, nothing happens.<br />

Private Sub Workbook_Open()<br />

If Weekday(Now) = 6 Then<br />

Msg = “Make sure you do your weekly backup!”<br />

748

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!