30.04.2017 Views

4523756273

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

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

Chapter 11: Automatic Procedures and Events<br />

171<br />

You can quickly access a sheet’s code window by right-clicking on the sheet’s<br />

tab and selecting View Code.<br />

The following example shows a simple procedure that is executed whenever<br />

a particular sheet is activated. This code simply pops up a message box that<br />

displays the name of the active sheet:<br />

Private Sub Worksheet_Activate()<br />

MsgBox “You just activated “ & ActiveSheet.Name<br />

End Sub<br />

Here’s another example that activates cell A1 whenever the sheet is activated:<br />

Private Sub Worksheet_Activate()<br />

Range(“A1”).Activate<br />

End Sub<br />

Although the code in these two procedures is about as simple as it gets,<br />

event-handler procedures can be as complex as you like.<br />

The following procedure (which is stored in the Code window for the Sheet1<br />

object) uses the Deactivate event to prevent a user from activating any other<br />

sheet in the workbook. If Sheet1 is deactivated (that is, another sheet is activated),<br />

the user gets a message and Sheet1 is activated.<br />

Private Sub Worksheet_Deactivate()<br />

MsgBox “You must stay on Sheet1”<br />

Sheets(“Sheet1”).Activate<br />

End Sub<br />

By the way, I don’t recommend using procedures, such as this one, that<br />

attempt to take over Excel. These so-called “dictator” applications can be<br />

very frustrating and confusing for the user. Rather, I recommend training the<br />

user how to use your application correctly.<br />

Activate and deactivate<br />

events in a workbook<br />

The previous examples use events associated with a specific worksheet. The<br />

ThisWorkbook object also handles events that deal with sheet activation and<br />

deactivation. The following procedure, which is stored in the Code window<br />

for the ThisWorkbook object, is executed when any sheet in the workbook is<br />

activated. The code displays a message with the name of the activated sheet.

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

Saved successfully!

Ooh no, something went wrong!