Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Excel_2010_Bible.pdf
Скачиваний:
26
Добавлен:
13.03.2015
Размер:
11.18 Mб
Скачать

CHAPTER

Working with

Excel Events

In the preceding chapters, I presented a few examples of VBA eventhandler procedures. These procedures are the keys to making your Excel applications interactive. This chapter provides an introduction to the concept of Excel events and includes many examples that you can

adapt to meet your own needs.

Understanding Events

Excel can monitor a wide variety of events and execute your VBA code when a particular event occurs. This chapter covers the following types of events.

Workbook events: These occur for a particular workbook. Examples include Open (the workbook is opened or created), BeforeSave (the workbook is about to be saved), and NewSheet (a new sheet is added). VBA code for workbook events must be stored in the ThisWorkbook code module.

Worksheet events: These occur for a particular worksheet. Examples include Change (a cell on the sheet is changed), SelectionChange (the cell pointer is moved), and Calculate (the worksheet is recalculated). VBA code for worksheet events must be stored in the code module for the worksheet (for example, the module named Sheet1).

Events not associated with objects: The final category consists of two useful application-level events: OnTime and OnKey. These work differently from other events.

IN THIS CHAPTER

Understanding events

Using workbook-level events

Working with worksheet events

Using non-object events

873

Part VI: Programming Excel with VBA

Entering Event-Handler VBA Code

Every event-handler procedure must reside in a specific type of code module. Code for workbooklevel events is stored in the ThisWorkbook code module. Code for worksheet-level events is stored in the code module for the particular sheet (for example, the code module named Sheet1).

In addition, every event-handler procedure has a predetermined name. You can declare the procedure by typing it, but a much better approach is to let the VB Editor do it for you, by using the two drop-down controls at the top of the window.

Figure 43.1 shows the code module for the ThisWorkbook object. Select this code module by double-clicking it in the Project window. To insert a procedure declaration, select Workbook from the objects list in the upper left of the code window. Then select the event from the procedures list in the upper right. When you do, you get a procedure “shell” that contains the procedure declaration line and an End Sub statement.

FIGURE 43.1

The best way to create an event procedure is to let the VB Editor do it for you.

For example, if you select Workbook from the objects list and Open from the procedures list, the VB Editor inserts the following (empty) procedure:

Private Sub Workbook_Open()

End Sub

Your event-handler VBA code goes between these two lines.

874

Chapter 43: Working with Excel Events

Some event-handler procedures contain an argument list. For example, you may need to create an event-handler procedure to monitor the SheetActivate event for a workbook. (This event is triggered when a user activates a different sheet.) If you use the technique described in the previous section, the VB Editor creates the following procedure:

Private Sub Workbook_SheetActivate(ByVal Sh As Object)

End Sub

This procedure uses one argument (Sh), which represents the activated sheet. In this case, Sh is declared as an Object data type rather than a Worksheet data type because the activated sheet also can be a chart sheet.

Your code can, of course, make use of information passed as an argument. The following example displays the name of the activated sheet by accessing the argument’s Name property. The argument becomes either a Worksheet object or a Chart object.

Private Sub Workbook_SheetActivate(ByVal Sh As Object)

MsgBox Sh.Name & “ was activated.”

End Sub

Several event-handler procedures use a Boolean argument named Cancel. For example, the declaration for a workbook’s BeforePrint event is

Private Sub Workbook_BeforePrint(Cancel As Boolean)

The value of Cancel passed to the procedure is FALSE. However, your code can set Cancel to TRUE, which cancels the printing. The following example demonstrates this:

Private Sub Workbook_BeforePrint(Cancel As Boolean)

Msg = “Have you loaded the 5164 label stock? “

Ans = MsgBox(Msg, vbYesNo, “About to print... “)

If Ans = vbNo Then Cancel = True

End Sub

The Workbook_BeforePrint procedure executes before the workbook prints. This procedure displays a message box asking the user to verify that the correct paper is loaded. If the user clicks the No button, Cancel is set to TRUE, and nothing prints.

Using Workbook-Level Events

Workbook-level events occur for a particular workbook. Table 43.1 lists the most commonly used workbook events, along with a brief description of each. Keep in mind that workbook event-han- dler procedures must be stored in the code module for the ThisWorkbook object.

875

Part VI: Programming Excel with VBA

TABLE 43.1

 

Workbook Events

Event

Action That Triggers the Event

 

 

Activate

The workbook is activated.

 

 

AddinInstall

The workbook is installed as an add-in.

 

 

AddinUninstall

The workbook is uninstalled as an add-in.

 

 

BeforeClose

The workbook is about to be closed.

 

 

BeforePrint

The workbook (or anything in it) is about to be printed.

 

 

BeforeSave

The workbook is about to be saved.

 

 

Deactivate

The workbook is deactivated.

 

 

NewSheet

A new sheet is created in the workbook.

 

 

Open

The workbook is opened.

 

 

SheetActivate

Any sheet in the workbook is activated.

 

 

SheetBeforeDoubleClick

Any worksheet in the workbook is double-clicked. This event occurs

 

before the default double-click action.

 

 

SheetBeforeRightClick

Any worksheet in the workbook is right-clicked. This event occurs

 

before the default right-click action.

 

 

SheetCalculate

Any worksheet in the workbook is calculated (or recalculated).

 

 

SheetChange

Any worksheet in the workbook is changed by the user.

 

 

SheetDeactivate

Any sheet in the workbook is deactivated.

 

 

SheetFollowHyperlink

Any hyperlink in the workbook is clicked.

 

 

SheetSelectionChange

The selection on any worksheet in the workbook is changed.

 

 

WindowActivate

Any window of the workbook is activated.

 

 

WindowDeactivate

Any workbook window is deactivated.

 

 

WindowResize

Any workbook window is resized.

 

 

The remainder of this section presents examples of using workbook-level events. All the example procedures that follow must be located in the code module for the ThisWorkbook object. If you put them into any other type of code module, they will not work.

Using the Open event

One of the most common monitored events is a workbook’s Open event. This event is triggered when the workbook (or add-in) opens and executes the Workbook_Open procedure. A Workbook_Open procedure is very versatile and is often used for the following tasks:

876

Chapter 43: Working with Excel Events

Displaying welcome messages.

Opening other workbooks.

Activating a specific sheet.

Ensuring that certain conditions are met; for example, a workbook may require that a particular add-in is installed.

Caution

Be aware that there is no guarantee that your Workbook_Open procedure will be executed. For example, the user may choose to disable macros. And if the user holds down the Shift key while opening a workbook, the workbook’s Workbook_Open procedure will not execute. n

The following is a simple example of a Workbook_Open procedure. It uses the VBA Weekday function to determine the day of the week. If it’s Friday, a message box appears to remind the user to perform a file backup. If it’s not Friday, nothing happens.

Private Sub Workbook_Open()

If Weekday(Now) = 6 Then

Msg = “Make sure you do your weekly backup!”

MsgBox Msg, vbInformation

End If

End Sub

What if you would like to activate a particular Ribbon tab automatically when a workbook is opened? Unfortunately, VBA can’t do much at all with the Excel Ribbon, and there is no direct way to activate a particular Ribbon tab. The next example uses the SendKeys statement to simulate keystrokes. In this case, it sends Alt+H, which is the Excel’s “keytip” equivalent of activating the Home tab of the Ribbon. Sending the F6 keystroke removes the keytip letters from the Ribbon.

Private Sub Workbook_Open()

Application.SendKeys (“%h{F6}”)

End Sub

The following example performs a number of actions when the workbook is opened. It maximizes the Excel window, maximizes the workbook window, activates the sheet named DataEntry, and selects the first empty cell in column A. If a sheet named DataEntry does not exist, the code generates an error.

Private Sub Workbook_Open()

Application.WindowState = xlMaximized

ActiveWindow.WindowState = xlMaximized

Worksheets(“DataEntry”).Activate

Range(“A1”).End(xlDown).offset(1,0).Select

End Sub

877

Part VI: Programming Excel with VBA

Using the SheetActivate event

The following procedure executes whenever the user activates any sheet in the workbook. The code simply selects cell A1. Including the On Error Resume Next statement causes the procedure to ignore the error that occurs if the activated sheet is a chart sheet.

Private Sub Workbook_SheetActivate(ByVal Sh As Object)

On Error Resume Next

Range(“A1”).Select

End Sub

An alternative method to handle the case of a chart sheet is to check the sheet type. Use the Sh argument, which is passed to the procedure.

Private Sub Workbook_SheetActivate(ByVal Sh As Object)

If TypeName(Sh) = “Worksheet” Then Range(“A1”).Select

End Sub

Using the NewSheet event

The following procedure executes whenever a new sheet is added to the workbook. The sheet is passed to the procedure as an argument. Because a new sheet can be either a worksheet or a chart sheet, this procedure determines the sheet type. If it’s a worksheet, it inserts a date and time stamp in cell A1.

Private Sub Workbook_NewSheet(ByVal Sh As Object)

If TypeName(Sh) = “Worksheet” Then _

Range(“A1”) = “Sheet added “ & Now()

End Sub

Using the BeforeSave event

The BeforeSave event occurs before the workbook is actually saved. As you know, choosing Office Save sometimes brings up the Save As dialog box — for example, when the file has never been saved or was opened in read-only mode.

When the Workbook_BeforeSave procedure executes, it receives an argument that enables you to identify whether the Save As dialog box will appear. The following example demonstrates this:

Private Sub Workbook_BeforeSave _

(ByVal SaveAsUI As Boolean, Cancel As Boolean)

If SaveAsUI Then

MsgBox “Use the new file-naming convention.”

End If

End Sub

878

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]