Handling Object Events

In simplest terms, an event is something that happens to an object. For example, the opening of an Excel workbook would be an event for that workbook. Don't confuse a method with an event, however. Yes, Word has an Open method that you can use to open a document, but this method only initiates the procedure; the actual process of the file being opened is the event. Note, too, that events can happen either programmatically (if the appropriate method is included in your code, such as Documents.Open) or by user intervention (if a command is selected, such as Office, Open).

In VBA, the event itself isn't as important as how your procedures respond to the event. In other words, you can write special procedures called event handlers that run every time a particular event occurs. In a Word document, for example, you can specify event handlers for both opening the file and closing the file. (Excel's Workbook object has an even larger list of events, including not just opening the file, but also activating the workbook window, saving the file, inserting a new worksheet, closing the file, and much more.)

For example, Figure 5.2 shows a module window for a document. (Specifically, it's the module window for the project's ThisDocument object.) Notice that the module window has two drop-down lists just below the title bar:

■ Object list—This is the list on the left and it tells you what kind of object you're working with. If you select (General) in this list, you can use the module window to enter standard VBA procedures and functions. If you select an object from this list, however, you can enter event handlers for the object.

■ Procedure list—This is the list on the right and it tells you which procedure is active in the module. If you select (General) in the Object list, the Procedure list contains all the standard VBA procedures and functions in the module. If you select an object in the Object list, however, the Procedure list changes to show all the events recognized by the object.

Figure 5.2

An example of an event procedure. Here,this procedure runs each time the document is opened.

Object list

Procedure list

Object list

Procedure list

Figure 5.2

An example of an event procedure. Here,this procedure runs each time the document is opened.

In Figure 5.2, I've selected Document in the Object list, so the Procedure list contains all the events recognized by the Document object. For the Open event, I've inserted a MsgBox statement into the Document_Open event handler. This statement will display a message each time the document is opened.

■ To learn how the MsgBox function works, see "Getting Input Using MsgBox," p.45.

0 0

Post a comment