Home > Articles > Data > Access

Responding to Form and Report Events

Access is an event-driven application. In Access, the occurrence of events triggers some action to occur. Events may be external or internal. External events are such things as a key being pressed or the mouse being moved. Internal events are such things as a form opening or closing, or an error occurring. You take control of Access by providing responses to events. These responses can be running a macro or a VBA event procedure.

NOTE

For a complete list of events, see the online help topic "Events and Event Properties Reference."

VBA event procedures (also known as event handlers) are subprocedures contained in class modules. Access automatically creates a class module when you write an event procedure to respond to an event related to a form or a report. Each form or report can have only one class module that contains all its event procedures.

NOTE

Previous versions of Access used the phrase code behind forms to refer to event procedures that respond to a form's or a report's events. This term is no longer used in Access 97 or Access 2000.

The class module that contains a form's event procedures is an integral part of that form. For that reason, if you make a copy of the form, the copy contains the class module with all its event procedures. The same is true for class modules that contain a report's event procedures. You can take advantage of this to save a lot of time if you have similar forms or reports within a single application, or if you have similar forms or reports in different applications.

The next few sections refer specifically to forms. Much of the information in those sections applies also to reports.

Creating Event Procedures for a Form's Events

You can create event procedures that run at the time a form opens or closes.

When you open a form, a sequence of events occurs in the order listed in Table 1.

Table 1 Events That Occur When a Form Opens

Event

Occurs

Open

After a form opens but before it displays values in its controls

Load

After values are displayed in the form's controls

Resize

Immediately after the Load event and also after the size of a form changes

Activate

When the form becomes active

GotFocus

Only if the form contains no visible controls or if all visible controls are disabled

Current

When a form is opened and also when the focus changes from one record to another

When you close a form, a sequence of events occurs in the order listed in Table 2.

Table 2 Events That Occur When a Form Closes

Event

Occurs

Unload

After a form is closed but before it is removed from the screen

LostFocus

Only if the form contains no visible controls or if all visible controls are disabled

Deactivate

When a form loses the focus to another form or to a Table, Query, Report, Macro, Module, or Database window

Close

After a form is closed and removed from the screen

When you switch between two open forms, the Deactivate event occurs for the currently active form and then the Activate event occurs for the newly active form.

It's very important to pay attention to when specific events occur and to the order in which they occur. For example, if you need an event procedure that runs when a form opens and also runs when you switch from one open form to another, you must create an event procedure that runs when the Activate event occurs. In contrast, if you want an event procedure to run when a form opens but not when you switch from one open form to another, you should create an event procedure that responds to the Open or Load event.

NOTE

After you've created an event procedure that responds to a form event, test that procedure carefully to make sure that it runs when you want it to and doesn't run when you don't want it to.

Creating an Event Procedure That Responds to a Form Event

A form has many events to which it can respond, as shown in Figure 3.

Figure 3 The Event tab in a form's Property sheet shows all the events to which a form can respond.

To gain a detailed understanding of how forms work, I urge you to become familiar with each of the events a form can respond to. It's not necessary to understand each event in detail; just become familiar with the nature of each event. When you want to use a specific event, you can access Help to get all the information you need.

NOTE

You can find detailed information about each of the events listed in Figure 3 by opening the "Events and Event Properties Reference" topic in Help. That topic contains an alphabetical listing of events. Click any event name to see information about that event.

To create an event procedure that responds to one of a form's events, follow these steps.

  1. Display the form in Design view. If necessary, choose View, Properties to display the Property sheet.

  2. Verify that the Property sheet's title bar contains the word Form. If not, click the button at the left end of the form's horizontal ruler.

  3. Display the Property sheet's Event tab, as previously shown in Figure 3.

  4. Click the name of the event for which you want to create an event procedure, such as On Load. A Builder button containing three dots appears at the right of the property box.

  5. Click the Builder button to display the Choose Builder dialog box.

  6. Select Code Builder and choose OK. Access displays the Visual Basic Editor (VBE) window shown in Figure 4.

Figure 4 The VBE window opens with the first and last statements of the new procedure displayed.

The first and last statements of the new procedure are known as a stub. It's up to you to place statements within the stub that control what happens when the event occurs. For example, if the form contains certain command buttons, you might want to enable and disable specific buttons so that only those that are useful immediately after the Load event occurs are enabled. Assuming that you have command buttons named cmdNew, cmdSave, cmdDelete, and cmdClose, you would enter code so that the command procedure consists of these statements:

Private Sub Form_Load()
   cmdNew.Enabled = True
   cmdSave.Enabled = False
   cmdDelete.Enabled = True
   cmdClose.Enabled = True
End Sub

Canceling an Event

Some—but, by no means all—event procedures allow you to cancel the associated event. For example, you can include code in a Form_Open event procedure to cancel the Open event; however, you can't include code in a Form_Load event procedure to cancel the Load event.

Figure 5 shows the stub for a Form_Open event procedure.

Figure 5 The first statement in a Form_Open event procedure includes the argument Cancel As Integer.

An argument is a value that's passed to a procedure. Arguments are listed in the first statement of a procedure after the procedure's name and are enclosed within a pair of parentheses. Each argument is a variable that has a name (Cancel, in this case) and a data type (Integer, in this case). Only one argument is shown in Figure 5. Procedures can have more than one argument, in which case each argument is separated from the next by a comma.

NOTE

Arguments are sometimes referred to as parameters. Because the word parameter has a special meaning in the context of queries within Access, I prefer to use argument for a value passed to a procedure.

When you create a stub for an event procedure such as Form_Open, the value of the Cancel argument is 0 (zero), which is the numerical equivalent of False. The argument's value remains unchanged unless you include code within the procedure to change it to True (or a numerical value other than 0). With the Cancel argument set to False, the argument has no effect—the Open event occurs, and whatever statements are in the Open event procedure are executed.

Within the Open event procedure, you can include this statement

Cancel = True

which has the effect of canceling the Open event. If this code is executed within the event procedure, the form doesn't open.

There's no point in writing a Form_Open event procedure in which the Cancel variable is always set to True—that would mean that the form never opens. Instead, the Cancel variable is set to True within an If control structure or some other control structure that tests for a certain condition(s). If that condition occurs, your code should display a message to the user and then set the Cancel variable to True. For example, if you didn't want anyone to be able to open a form on a Sunday, you could write a Form_Open event procedure such as that in Listing 1.

Listing 1  VBA Code to Demonstrate the Use of the Cancel Argument

Private Sub Form_Open(Cancel As Integer)
   If Weekday(Date) = vbSunday Then
      MsgBox "You can't open this form on a Sunday!"
      Cancel = True
   End If
      'Insert code here to control what happens when the
      'form opens on any day other than Sunday
End Sub

The first statement in the If control structure makes use of two Access functions. The Date function returns the current system date. The Weekday function returns the number of the day of the week. If the current date corresponds to a Sunday, Weekday(Date) returns a value of 1 (one), which corresponds to the Visual Basic intrinsic constant vbSunday. Consequently, the condition is true, so the two statements within the If control structure execute. For any other day, the condition is not true, so the two statements within the If control structure don't execute, the value of the Cancel variable remains False, and the form opens Argument.

Responding to Control Events

Controls, as you know, are objects that you place on forms and reports. These objects include labels, text boxes, option buttons, check boxes, command buttons, list boxes, combo boxes, and more. Each of these controls can respond to various events. For example, the events to which command buttons can respond are listed in Figure 6.

Figure 6 These are the events to which a command button can respond.

Although the On Click event for a command button is the event you'll use most frequently, take some time to understand the other events you can use.

You can create event procedures for controls in the same way that you create event procedures for forms and reports, as described in the section "Creating Event Procedures for a Form's Events," previously in this chapter.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020