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.

Part VI<br />

Programming Excel with VBA<br />

Using the BeforeSave event<br />

The BeforeSave event occurs before the workbook is actually saved. As you know, choosing <strong>Office</strong> ➪<br />

Save sometimes brings up the Save As dialog box — for example, when the file has never been saved or was<br />

opened in read-only mode.<br />

When the Workbook_BeforeSave procedure executes, it receives an argument that enables you to identify<br />

whether the Save As dialog box will appear. The following example demonstrates this:<br />

Private Sub Workbook_BeforeSave _<br />

(ByVal SaveAsUI As Boolean, Cancel As Boolean)<br />

If SaveAsUI Then<br />

MsgBox “Use the new file-naming convention.”<br />

End If<br />

End Sub<br />

When the user attempts to save the workbook, the Workbook_BeforeSave procedure executes. If the<br />

save operation brings up the Save As dialog box, the SaveAsUI variable is True. The preceding procedure<br />

checks this variable and displays a message only if the Save As dialog box is displayed. In this case, the message<br />

is a reminder about how to name the file.<br />

The BeforeSave event procedure also has a Cancel variable in its argument list. If the procedure sets the<br />

Cancel argument to True, then the file is not saved.<br />

Using the BeforeClose event<br />

The BeforeClose event occurs before a workbook is closed. This event often is used in conjunction with<br />

a Workbook_Open event handler. For example, use the Workbook_Open procedure to initialize items in<br />

your workbook and use the Workbook_BeforeClose procedure to clean up or restore settings to normal<br />

before the workbook closes.<br />

If you attempt to close a workbook that hasn’t been saved, Excel displays a prompt that asks whether you<br />

want to save the workbook before it closes.<br />

A problem can arise from this event. By the time the user sees this message, the<br />

BeforeClose event has already occurred. This means that the Workbook_BeforeClose<br />

procedure has already executed.<br />

CAUTION<br />

Working with Worksheet Events<br />

The events for a Worksheet object are some of the most useful. As you’ll see, monitoring these events can<br />

make your applications perform feats that otherwise would be impossible.<br />

Table 43.2 lists the worksheet events, with a brief description of each. Remember that these event procedures<br />

must be entered into the code module for the sheet. These code modules have default names like<br />

Sheet1, Sheet2, and so on.<br />

750

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

Saved successfully!

Ooh no, something went wrong!