Responding to Events

 < Day Day Up > 

One of the key concepts that Access developers need to understand is that Access is an event-driven programming environment. That means that VBA code doesn't just arbitrarily run when it wants to. Rather, code runs in response to events: users clicking buttons, new records being loaded into forms, and so on.

You might have already dug into Access events, depending on how much you did with macro programming in the past. But these topics are so central that this chapter reviews the basics. In particular, you need to understand that events happen in a specific order, and that each one has a specific purpose.

Before the reference topics, it's important to review one more time just how all the pieces fit together. As an example of an event, you look at the Open Report button on the Billing Report Setup form. When you open the form in Design view, you see that the name of the button is cmdOpenReport. Looking at the Properties window for cmdOpenReport, you can then see that the On Click property of this button is set to [Event Procedure]. That tells Access that it should send click events from this button to VBA to be handled.


If you see anything other than [Event Procedure] in an event property, it's probably the name of a macro that's called when the event occurs. In that case, VBA isn't involved in handling the event.

Knowing that this event is handled by a VBA event procedure, you need to turn to the VBA editor to see the details. One quick way to get to the appropriate procedure is to click in the On Click property entry in the Properties window, and then click the ellipsis button that shows up next to the [Event Procedure] entry. Click this button to jump to VBA. In this case, you see the following procedure in the Form_BillingReportSetup module:


 Private Sub cmdOpenReport_Click()   On Error GoTo HandleErr   DoCmd.OpenReport "BillingReport", acViewPreview ExitHere:   Exit Sub HandleErr:   MsgBox "Error " & Err.Number & ": " & _    Err.Description & " in cmdBillingReport_Click"   Resume ExitHere End Sub 

All the pieces need to be in place for VBA to handle an event:

  • The appropriate property must have the [Event Procedure] setting.

  • The code must be in the correct module (the one that's attached to the form or report where the event will occur).

  • The procedure must be named with the pattern objectname_eventname.


VBA automatically fills in the [Event Procedure] entries in the Properties window if you write code with the correct procedure name in a module.

There's one more requirement for some events that you'll see later in this chapter: if the event includes arguments, the event procedure declaration must match the arguments that the event sends.

     < Day Day Up > 

    Automating Microsoft Access with VBA
    Automating Microsoft Access with VBA
    ISBN: 0789732440
    EAN: 2147483647
    Year: 2003
    Pages: 186 © 2008-2017.
    If you may any questions please contact us: