Responding to Events

CHAPTER 5

Responding to Events

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

Rather than running entire programs line by line, Microsoft® Access applications run macros and event procedures in response to specific events for particular objects, such as a change to data in a field, or a mouse click on a command button. Understanding the events Access recognizes can help you create powerful, flexible, and responsive applications. This chapter describes the Access event model and shows you how to manage events in your applications.

Chapter Contents

Working with Events   

Managing Events in Your Application   

Canceling Events   

Default Events   

Working with Events

An event is a specific action that occurs with a certain object, such as a form or report. Typically events are caused by a user action such as clicking a button or pressing a key.  Being that Microsoft Access is an event-driven application, many events are available so that you can add your own custom response to an event that occurs. Objects in Access respond to the following types of events:

  • Mouse clicks

  • Changes in data or data selection

  • Keystrokes a user types

  • Objects receiving or losing the focus

  • Forms or reports being opened, closed, or resized

  • Reports being printed or formatted

  • Run-time errors

The focus is the application’s ability to receive input or respond to a user’s mouse or keyboard actions. In Microsoft® Windows®, only one item at a time can have the focus. For example, when a user types, characters appear in a text box only if the text box has the focus. Which object or control receives the focus is determined by a user’s actions, such as clicking in a text box or pressing TAB to move to a control. Before a user acts, settings made at design time determine which control has the focus. For example, when a user first opens or switches to a form, the control that has the focus is the one with the lowest TabIndex property setting. You can also explicitly set the focus in code by using the SetFocus method.

****See Also  **** For more information about the TabIndex property or the SetFocus method, type tabindex property or setfocus method in the Office Assistant or on the Answer Wizard tab in the Help window, and then click Search.

You can see the events that are generated in Access by opening the ShowEvents form in the Orders sample application. You can download the Orders sample application and associated Help files from the Microsoft Developer Network (MSDN) Online Web site. The ShowEvents form, a special version of the Orders form, records each event as it occurs. An accompanying EventHistory form lists the name of the event and the type or name of the object on which the event occurred, using the format object_event. For example, if a Click event occurs on the ShowEvents subform, the line “[Subform]Form_Click” is added to the Events list on the EventHistory form.

The EventHistory form lists events in reverse order, with the most recent event at the top of the list. The form lists all events except MouseMove events, which occur each time you move the mouse pointer, and would quickly fill up the list if they were included.

By default, Access automatically responds to events with built-in behaviors defined for each object. For example, when a user enters or changes data in a text box, Access automatically checks to make sure the data is of the right type.

In addition, each object in Access has a set of event properties that correspond to each event to which the object can respond. For example, the following table lists some of the event properties and corresponding events for a check box.

Event property Event
OnGotFocus GotFocus
OnKeyDown KeyDown
OnKeyPress KeyPress
OnKeyUp KeyUp
OnLostFocus LostFocus
OnMouseDown MouseDown
OnMouseMove MouseMove
OnMouseUp MouseUp

****See Also  **** For more information about events and event properties, type events reference in the Office Assistant or on the Answer Wizard tab in the Help window, and then click Search.

You can specify a further response to an event by setting the object’s corresponding event property. When an event occurs that an object can respond to, Access uses the setting of the object’s corresponding event property to determine how to respond:

  • If the event property is blank, Access responds to the event only with its built-in behavior.

  • If the event property is set to the name of a macro, and the event can’t be canceled, Access first performs the built-in behavior, and then runs the macro. If the event property is set to the name of a macro and the event can be canceled, Access first runs the macro, and then performs the built-in behavior.

  • If the event property is set to [Event Procedure], and the event can’t be canceled, Access first performs the built-in behavior, and then calls the appropriate event procedure. If the event property is set to [Event Procedure], and the event can be canceled, Access first calls the appropriate event procedure, and then performs the built-in behavior.

****See Also  **** For information about which events can be canceled, see “Canceling Events” later in this chapter.

For example, when you click a command button whose OnClick event property is set to a macro, Access:

  1. Makes the button appear pressed in momentarily—the built-in behavior when a Click event occurs on a command button. Note that the Click event can’t be canceled.

  2. Runs the macro.

When the event property is set to [Event Procedure], Access responds to the event by running the appropriate event procedure in addition to performing its built-in behavior. Event procedures are named for the event and the object for which they occur, in the format object_event. For example, if a user clicks the Products command button, Access:

  1. Makes the Products command button appear pressed in momentarily—its built-in behavior.

  2. Runs the Products_Click event procedure.

****Note  **** When you create an event procedure, Access automatically sets the appropriate event property to [Event Procedure] if the property doesn’t already have a setting. As an alternative, you can set the property to [Event Procedure], and then create the event procedure separately. For more information about creating an event procedure, see Chapter 2, “Introducing Visual Basic for Applications” in this book, or see Chapter 7, “Getting the Most Out of Visual Basic for Applications,” in the Microsoft Office 2000/Visual Basic Programmer's Guide (Microsoft Press, 1999). You can also find this guide in the Office Developer Documentation section of the Microsoft Developer Network (MSDN) Online Library.

You can also have Access call a function in response to an event. To do so, add to the appropriate event procedure an expression that calls the function, or type an equal sign (=) followed by the function name as the event property setting in the property sheet.

For example, to call the CheckValues function when a form opens, you can type the following OnOpen property setting in the form’s property sheet:

=CheckValues()

****Note  **** Using an expression that calls a function as an event property setting for a form or control is useful when you want to use code and the form’s HasModule property is set to No so that it loads more quickly. Also, always make sure to include the parentheses with the function call. For more information, see “Optimizing Form Loading and Paging” in Chapter 7, “Optimizing Your Application.”

The macros and Visual Basic® for Applications (VBA) code that Access runs in response to events control how the objects in your application work together. By managing the events, macros, and VBA code that Access runs in response to events, you can create powerful, flexible, and responsive database applications.

Managing Events in Your Application

Most operations in Access involve a sequence of events. For example, the process of opening a form usually includes the following sequence:

  1. When the form opens, but before the first record is displayed, the Open event occurs.

  2. When the form opens and its records are displayed, the Load event occurs.

  3. When the form becomes the active window, the Activate event occurs.

Other events also occur when the previously active window becomes inactive and the focus moves to an object in the new active window. The full sequence of events in typical situations is explored later in this chapter.

****See Also  **** For more information about the order of events, type order of events in the Office Assistant or on the Answer Wizard tab in the Help window, and then click Search.

Because each step in opening a form is a separate event, your application can run a macro or a procedure exactly when you want it to. For example, your application can close another window or preset the focus in the new active window before the first record is displayed. Or it can display a custom toolbar on the form when its window becomes active.

You can also cancel many events. For example, you can prevent a form from opening if certain conditions are not met by including code in the form’s Open event procedure that cancels the Open event when an expression evaluates to True.

****See Also  **** For more information about canceling events, see “Canceling Events” later in this chapter.

Access events fall into several categories. The following table summarizes these event categories.

Event category Events Occur when
Window events Close, Load, Open, Resize, Unload A user or code opens, resizes, or closes a form or report.
Focus events Activate, Deactivate, Enter, Exit, GotFocus, LostFocus Objects receive or lose the focus, or become active or inactive.
Data events AfterDelConfirm, AfterInsert, AfterUpdate, BeforeDelConfirm, BeforeInsert, BeforeUpdate, Change, Current, Delete, NotInList, Updated, Dirty A user or code enters, deletes, or changes data in a form or control, or moves the focus from one record to another.
Mouse events Click, DblClick, MouseDown, MouseMove, MouseUp A user performs a mouse action, such as clicking or double-clicking.
Keyboard events KeyDown, KeyPress, KeyUp A user types on the keyboard, or keys are sent using the SendKeys action or the SendKeys statement.
Print events Format, NoData, Page, Print, Retreat A report is being printed, or is being formatted for printing.
Filter events ApplyFilter, Filter A user creates, applies, or removes a filter for a form.
Error and Timing events Error, Timer Access or the Jet database engine encounters an error, or a specified time interval passes.

****See Also  **** For more information about each of these events and examples of how to respond to them in your application, type events reference or the name of a particular event in the Office Assistant or on the Answer Wizard tab in the Help window, and then click Search.

Working with Forms and Controls

Opening a form triggers a sequence of events, including the Open, Load, Resize, and Activate events. In addition, if no control on the form can receive the focus, a GotFocus event occurs for the form itself. Other events occur as you work with the form and its controls. You can write macros or VBA code for any of these events, so you have a fine degree of control over how your application behaves.

****Note  **** To see the sequence of events that occurs when you work with forms and controls, open the ShowEvents form in the Orders sample application.

Because opening forms, moving between forms, and working with controls are some of the most common operations in an Access application, understanding the order of these events is one of the keys to effective application development. This section describes the sequence of events for some common form and control operations.

Opening and Closing a Form

When you first open a form that contains an active control—one that can receive the focus—the following sequence of events occurs for the form:

If there are no active controls on the form, Access also triggers a GotFocus event for the form, after the Activate event, but before the Current event.

When you close a form that contains an active control, Access triggers the following sequence of events for the form:

If there are no active controls on the form, Access triggers a LostFocus event for the form after the Unload event, but before the Deactivate event.

Entering and Exiting a Control

When you open a form that contains one or more active controls, an Enter event occurs, followed by a GotFocus event, for the control receiving the focus. These events occur after the form’s Activate and Current events:

Both events occur when a control first receives the focus. If you switch to a different form and then return to the same control on the first form, Access triggers a GotFocus event for the control, but not an Enter event.

When you exit a control—for example, when you select another control on the same form—the following events occur for the control:

Switching Between Open Forms

When you switch between two open forms that contain active controls, Access triggers a Deactivate event on the first form and an Activate event on the second form:

****Note  **** An Open event doesn’t occur on a form that is already open but not activated, whether you switch to the form or run a macro that specifies the form in an OpenForm action. If you want your application to run the code in a form’s Open event procedure when the form is already open, you can:

  • Add the code to the form’s Activate event procedure instead of the Open event procedure, if timing isn’t critical. The Activate event occurs both when you open a form and when you make it the active form, so the code is sure to run.

  • Determine if the form is open by checking the value returned by the IsLoaded function in the UtilityFunctions module of the Orders sample application. Do this before running the macro that contains the OpenForm action.

If there are no active controls on the forms, Access also triggers the LostFocus and GotFocus events:

Example: Switching Between Controls on Different Forms

This example shows the sequence of events that are triggered in a typical scenario while you work with forms and controls.

****Step One: Open a form  **** Open the form Form1, whose first active control is Control1.

****Step Two: Open a second form  **** Open the form Form2, whose first active control is Control2.

There is no Exit(Control1) event, because the object that receives the focus is on a different form.

****Step Three: Return to the first form  **** Click on the first form.

Control1 now has the focus. There is no Enter(Control1) event because Control1 had the focus when Form1 was last active.

****Step Four: Click another control on the first form  **** Click a different control, Control3, on the second form.

****Step Five: Click another control on the second form  **** Click a different control, Control4, on the second form.

Responding to Keystrokes

When you press a key, Access triggers the KeyDown, KeyPress, and KeyUp events for the form or control that has the focus. When a control has the focus, you’ll normally want the control to receive all keystrokes when changing data in a text box.

****See Also  **** For information about responding to changes to text and data, see the following section, “Working with Data.”

In some cases, however, you’ll want to respond to specific keys pressed in a form, regardless of which control has the focus. For example, you may want to perform some action whenever the user presses a key combination such as CTRL+Y. You can make sure that the form receives all key events, even those that occur in controls, by setting the KeyPreview property for the form to Yes. With this property setting, all key events occur first for the form, and then for the control that has the focus.

You can respond to specific keys in the form’s KeyPress, KeyDown, or KeyUp events. The KeyPress event responds only to the ANSI characters generated by the keyboard. ANSI characters are generated by the following keys and key combinations: any printable keyboard character, CTRL+A through CTRL+Z, ENTER, CTRL+ENTER, BACKSPACE, CTRL+BACKSPACE, and TAB. The KeyPress event ignores all other keystrokes. In most cases, it is simplest to use only the KeyPress event to respond to keyboard events.

The following sample code demonstrates how to respond to the CTRL+Y key combination in a form by using the KeyPress event. Note that you can prevent the control from getting keystrokes you respond to by setting the KeyAscii argument to zero.

Private Sub Form_KeyPress (KeyAscii As Integer)

   ' ANSI character code for CTRL+Y.
   Const CTRL_Y_CODE = 25

On Error GoTo ErrorHandler

   If KeyAscii = CTRL_Y_CODE Then
      MsgBox "You pressed Ctrl+Y", vbInformation
      KeyAscii = 0      ' Do not send key on to control.
   End If

   Exit Sub

ErrorHandler:
   MsgBox "Error #: " & Err.Number & vbCrLf & vbCrLf & Err.Description
End Sub

The KeyDown and KeyUp events work on a lower level by responding to events generated by the keys themselves being pressed and released. Use KeyDown and KeyUp events if you need to respond to keys that don’t generate ANSI characters, such as the function keys (F1 through F12), or if you need to respond to key combinations that include the SHIFT, ALT, and CTRL keys (except the CTRL key combinations that respond to the KeyPress event).

****See Also  **** For more information about responding to keystrokes by using the KeyUp and KeyDown events, type keyup or keydown in the Office Assistant or on the Answer Wizard tab in the Help window, and then click Search.

Working with Data

You can use data events in your application to respond to many types of changes to records and data. For example, the application can run a macro or an event procedure in response to:

  • Changes to text in a text box or combo box.

  • Updates to data in a control or record.

  • Insertions or deletions of records, either before or after the record is inserted or deleted, or before or after a deletion is confirmed.

****Note  **** Some events do not occur when you use VBA code to manipulate data in your application—for example, the Change event, the BeforeInsert event, and the AfterInsert event. To see the sequence of events that occurs when you work with data, open the ShowEvents form in the Orders sample application.

Changing Text in a Text Box or Combo Box

When you change text in a text box or combo box, a Change event occurs. The event occurs whenever the contents of a control changes, but before you move to a different control or record. For example, when you delete a character in a text box by pressing the BACKSPACE key, Access triggers the following sequence of events:

If you then type one or more characters in the text box, Access recognizes the same sequence of events for each keystroke. Note that the KeyPress event doesn’t occur if you delete a character by using the DELETE key, only if you use the BACKSPACE key.

For bound forms, the first time that data changes in the current record, the form’s Dirty event will occur between the KeyPress and Change events of any control on the form.

The Change event doesn’t occur when a value changes in a calculated control, or when you select an item from a combo box list.

****See Also  **** For more information about using a calculated control in an Access application, type calculated control in the Office Assistant or on the Answer Wizard tab in the Help window, and then click Search.

Updating Data in a Control or Record

When you update data in a control by moving to a different control on the form, Access triggers the BeforeUpdate and AfterUpdate events for the control. The BeforeUpdate event occurs just before the data is updated; the AfterUpdate event occurs after the update.

For example, if you update data in a text box (TB1) by deleting a character, then click a different text box (TB2), Access triggers the following sequence of events:

If you update a control or record by moving to a different record or by clicking Save Record on the Records menu, the BeforeUpdate and AfterUpdate events for both the control and the form occur. For example, if you delete a character in a text box and then click Save Record on the Records menu, the following sequence of events occurs:

When you update a control or record by moving to a different record, Access triggers several events after the BeforeUpdate and AfterUpdate events for the control and form: It triggers Exit and LostFocus events for the control losing the focus, the Current event for the new record, and Enter and GotFocus events for the control receiving the focus.

For bound forms, the first time that data changes in the current record, the form’s Dirty event will occur between the KeyPress and Change events of any control on the form.

Inserting Records

When you enter data in a new record by way of the user interface, Access triggers a BeforeInsert event when you first enter data in the record, and an AfterInsert event when the record is saved.

Example: Entering Data in a New Record

This example shows the sequence of events that Access triggers in a typical scenario when you enter data in a new record.

****Step One: Enter text in the first field of a new record  **** After clicking Data Entry on the Records menu of a form to display a blank record, type a character in a text box (TB1).

For the first data entered in a new record in a bound form, the form’s Dirty event will occur between the form’s BeforeInsert event and the control’s Change event.

****Step Two: Move to another field of the same record and enter text  **** Click another text box (TB2) on the form and type a character.

****Step Three: Save the new record  **** Click Save Record on the Records menu.

Deleting Records

When you select a record and delete it (by pressing the DELETE key, or by clicking Delete or DeleteRecord on the Edit menu), Access triggers the Delete event, and then the Current event. If you select multiple records and delete them, the Delete event occurs once for each record that you have selected, and then Access triggers the Current event. Unless you cancel the Delete event, Access also triggers BeforeDelConfirm and AfterDelConfirm events. You use these events to control how record deletions are confirmed.

For example, when you select a record on a form and delete it, Access by default:

  • Triggers the following sequence of events:

  • Displays the following dialog box after the BeforeDelConfirm event.

If you want, you can prevent this dialog box from appearing in two ways. You can cancel the BeforeDelConfirm event, in which case the deletion is canceled. Or you can set the Response argument of the BeforeDelConfirm event procedure to acDataErrContinue, in which case the deletion is confirmed.

Your BeforeDelConfirm event procedure can display a custom dialog box and handle the user’s responses. The following example demonstrates how to use a custom dialog box to ask the user whether they want to cancel or proceed with the record deletion.

Private Sub Form_BeforeDelConfirm(Cancel As Integer, Response As Integer)

   Dim strMessage As String
   Dim intResponse As Integer

On Error GoTo ErrorHandler

   ' Display the custom dialog box.
   strMessage = "Would you like to delete the current record?"
   intResponse = MsgBox(strMessage, vbYesNo + vbQuestion, _
               "Continue delete?")

   ' Check the response.
   If intResponse = vbYes Then
      Response = acDataErrContinue
   Else
      Cancel = True
   End If

   Exit Sub

ErrorHandler:
   MsgBox "Error #: " & Err.Number & vbCrLf & vbCrLf & Err.Description
End Sub

Canceling Events

Under some circumstances, you may want to include code in an event procedure that cancels the associated event. For example, you may want to include code that cancels the Open event in an Open event procedure for a form, preventing the form from opening if certain conditions are not met.

You can cancel the following events:

BeforeDelConfirm Format
BeforeInsert BeforeUpdate
DblClick Dirty
Open Delete
Print Unload
Exit Filter
ApplyFilter NoData
KeyPress (only with a macro) MouseDown (only the right mouse button, and only with a macro)

You cancel an event by specifying a macro containing the CancelEvent action as the corresponding event property setting or, with the exception of the MouseDown and KeyPress events, by setting an event procedure’s Cancel argument to True. For example, to prevent a form from opening, you can:

  • Create a macro that carries out the CancelEvent action, and then specify that macro as the form’s OnOpen event property setting.

  • Add code to the form’s Open event procedure that sets the procedure’s Cancel argument to True.

****See Also  **** For more information about the CancelEvent action, type cancel event in the Office Assistant or on the Answer Wizard tab in the Help window, and then click Search.

You can see an example of canceling an Unload event in the EventHistory form of the Orders sample application. Because the EventHistory form is required by the ShowEvents form, it’s important to close the ShowEvents form before closing the EventHistory form. To ensure that the ShowEvents form isn’t left open without the EventHistory form, the EventHistory form’s Unload event procedure cancels the Unload event if you try to close it when the ShowEvents form is open.

Private Sub Form_Unload (Cancel As Integer)
' Reminds the user to close the ShowEvents form if it's open.

   Dim strMsg As String
   Dim bytAnswer As Byte

On Error GoTo ErrorHandler

   If IsLoaded("ShowEvents") Then
      strMsg = "Do you want to close the ShowEvents form?"
      bytAnswer = MsgBox(strMsg, vbOKCancel + _
                  vbDefaultButton2 + vbQuestion)
      If bytAnswer = vbOK Then
         DoCmd.Close acForm, "ShowEvents"
      Else
         Cancel = True
      End If
   End If

Exit Sub

ErrorHandler:
   MsgBox "Error#:  " & Err.Number & vbCrLf & vbCrLf & Err.Description
End Sub

Default Events

Many types of objects in Access are most often associated with a particular event. For example, command buttons are most commonly associated with the Click event.

To make it easier for you to program responses to these default events, the shortcut menu includes the Build Event command. When you right-click an object, and then click Build Event, Access displays the Choose Builder dialog box. If you click Macro Builder, Access sets the object’s default event property to the name of the macro you create. If you click Code Builder, Access opens the Code window and displays the object’s default event procedure.

****Tip  **** If you don't want to see the Choose Builder dialog box, and always want to open the Code window by using an empty event property's Build button, you can select the Always Use Event Procedures check box on the Forms/Reports tab of the Options dialog box (Tools menu).

****Note  **** No event occurs for an object by default. The default event is only the event procedure that Access displays when you click Build Event on the shortcut menu. Access always runs the procedure associated with an object and the event that actually occurs, regardless of the object’s default event.

The following table shows the default events for Access objects that have them.

Object Default event
Form Load
Report Open
Bound object frame Updated
Unbound object frame Updated
Image control Click
Chart Updated
Check box (not in option group) Click
Check box (in option group) GotFocus
Command button Click
Label Click
List box BeforeUpdate
Option button (not in option group) Click
Option button (in option group) GotFocus
Rectangle Click
Option group BeforeUpdate
Toggle button (not in option group) Click
Toggle button (in option group) GotFocus
Subform/subreport Enter
Text box BeforeUpdate
Combo box BeforeUpdate
Tab control Click
Page Click
Section (Report) Format
Section (Form) Click