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 (by including the appropriate method in your code, such as File.Open ) or by user intervention (by selecting a command, such as File, 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 will 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?/span> 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?/span> 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.

graphics/05fig02.jpg

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. (I show you how to use MsgBox in Chapter 12, "Interacting with the User." )



Absolute Beginner's Guide to VBA
Absolute Beginners Guide to VBA
ISBN: 0789730766
EAN: 2147483647
Year: 2003
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net