18.11.2014 Views

Microsoft Office

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Working with Excel Events 43<br />

Your code can, of course, make use of information passed as an argument. The following example displays<br />

the name of the activated sheet by accessing the argument’s Name property. The argument becomes either a<br />

Worksheet object or a Chart object.<br />

Private Sub Workbook_SheetActivate(ByVal Sh As Object)<br />

MsgBox Sh.Name & “ was activated.”<br />

End Sub<br />

Several event-handler procedures use a Boolean argument named Cancel. For example, the declaration<br />

for a workbook’s BeforePrint event is<br />

Private Sub Workbook_BeforePrint(Cancel As Boolean)<br />

The value of Cancel passed to the procedure is False. However, your code can set Cancel to True,<br />

which cancels the printing. The following example demonstrates this:<br />

Private Sub Workbook_BeforePrint(Cancel As Boolean)<br />

Msg = “Have you loaded the 5164 label stock? “<br />

Ans = MsgBox(Msg, vbYesNo, “About to print... “)<br />

If Ans = vbNo Then Cancel = True<br />

End Sub<br />

The Workbook_BeforePrint procedure executes before the workbook prints. This procedure displays a<br />

message box asking the user to verify that the correct label stock is loaded. If the user clicks the No button,<br />

Cancel is set to True, and nothing prints.<br />

Using Workbook-Level Events<br />

Workbook-level events occur for a particular workbook. Table 43.1 lists the most commonly used workbook<br />

events, along with a brief description of each. Keep in mind that workbook event-handler procedures<br />

must be stored in the code module for the ThisWorkbook object.<br />

TABLE 43.1<br />

Event<br />

Activate<br />

AddinInstall<br />

AddinUninstall<br />

BeforeClose<br />

BeforePrint<br />

BeforeSave<br />

Deactivate<br />

NewSheet<br />

Workbook Events<br />

Action That Triggers the Event<br />

The workbook is activated.<br />

The workbook is installed as an add-in.<br />

The workbook is uninstalled as an add-in.<br />

The workbook is about to be closed.<br />

The workbook (or anything in it) is about to be printed.<br />

The workbook is about to be saved.<br />

The workbook is deactivated.<br />

A new sheet is created in the workbook.<br />

continued<br />

747

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

Saved successfully!

Ooh no, something went wrong!