Automating Microsoft Access with VBA
< Day Day Up > |
There's one more part of working with objects that you haven't read about yet: dealing with events. You're probably familiar with events from working in the Access user interface. Events provide "hooks" that let you run your own code when something happens. For example, buttons have a Click event, and when the user clicks a button in your application, you can run a macro in response. However, it turns out that running macros in response to events is a shortcut invented by the Access team to make it possible to construct reasonably complex applications without writing any code. Most professional developers avoid the use of macros for several reasons (notably that macros do not implement any error trapping). Instead of using macros to respond to events, you can use event procedures, which are special pieces of VBA code. In the TimeTrack sample application, all the buttons use macros to perform their work. Let's convert one of these to use an event procedure so that you can see the syntax involved.
VBA hooks up event procedures to events based on a naming convention and the location of the code. In this case, the code is in the module for the Switchboard form, and the procedure is named using the pattern objectname_eventname. As Figure 8.7 shows, there are also cues in the VBA user interface that let you know when you're working in an event procedure. If you want to construct a new event procedure without using the Access interface, you can select the appropriate object and event from the drop-down lists in the VBA editor. Figure 8.7. An event procedure in the VBA editor.
This event procedure introduces one more of the built-in Access objects: the DoCmd object. You can think of the DoCmd object as a bridge between the world of Access macros and that of VBA code. The DoCmd object has no properties, but it implements one method for each of the actions that you can include in an Access macro. Anything that you can do with an Access macro, you can do in VBA code with the DoCmd object.
|
< Day Day Up > |