30.04.2017 Views

4523756273

Create successful ePaper yourself

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

Chapter 11: Automatic Procedures and Events<br />

167<br />

In this case, Sh is the argument passed to the procedure and is a variable that<br />

represents the sheet in the activated workbook. Examples in this chapter<br />

clarify this point.<br />

Introductory Examples<br />

In this section, I provide a few examples so that you can get the hang of this<br />

event-handling business.<br />

The Open event for a workbook<br />

One of the most commonly used events is the Workbook Open event. Assume<br />

that you have a workbook that you use every day. The Workbook_Open<br />

procedure in this example is executed every time the workbook is opened.<br />

The procedure checks the day of the week; if it’s Friday, the code displays a<br />

reminder message for you.<br />

To create the procedure that is executed whenever the Workbook Open<br />

event occurs, follow these steps:<br />

1. Open the workbook.<br />

Any workbook will do.<br />

2. Press Alt+F11 to activate the VBE.<br />

3. Locate the workbook in the Project window.<br />

4. Double-click the project name to display its items, if necessary.<br />

5. Double-click the ThisWorkbook item.<br />

The VBE displays an empty Code window for the ThisWorkbook object.<br />

6. In the Code window, select Workbook from the Object (left) dropdown<br />

list.<br />

The VBE enters the beginning and ending statements for a Workbook_<br />

Open procedure.<br />

7. Enter the following statements, so the complete event-procedure looks<br />

like this:<br />

Private Sub Workbook_Open()<br />

Dim Msg As String<br />

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

Msg = “Today is Friday. Make sure that you “<br />

Msg = Msg & “do your weekly backup!”<br />

MsgBox Msg<br />

End If<br />

End Sub

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

Saved successfully!

Ooh no, something went wrong!