Microsoft Access 2021 Programming Pocket Primer - Julitta Korol - E-Book

Microsoft Access 2021 Programming Pocket Primer E-Book

Julitta Korol

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

This book, part of the successful Pocket Primer series, is designed for those who need to master Access programming fundamentals quickly. You only need this concise guide to get started and feel comfortable with VBA. The concepts learned here also apply to Excel programming. The book is divided into nine chapters, each progressively introducing you to programming in Microsoft Access 2021.
Beginning with an introduction to Access VBA, the book covers the Visual Basic Editor, fundamental VBA programming concepts, and how to create both built-in and custom functions. You will learn to add decision-making capabilities and repeating actions to your programs, manage multiple values using arrays and collections, and utilize built-in tools for testing and debugging your code.
This structured approach ensures that by the end of the course, you will have a solid foundation in Access programming. The companion files provide all the hands-on resources needed to complete chapter projects, making this an essential resource for mastering Access VBA efficiently and effectively.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 317

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



MICROSOFT®Access® 2021Programming

Pocket Primer

LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY

By purchasing or using this book and disc (the “Work”), you agree that this license grants permission to use the contents contained herein, including the disc, but does not give you the right of ownership to any of the textual content in the book / disc or ownership to any of the information or products contained in it. This license does not permit uploading of the Work onto the Internet or on a network (of any kind) without the written consent of the Publisher. Duplication or dissemination of any text, code, simulations, images, etc. contained herein is limited to and subject to licensing terms for the respective products, and permission must be obtained from the Publisher or the owner of the content, etc., in order to reproduce or network any portion of the textual material (in any media) that is contained in the Work.

Mercury Learning and Information (“MLI” or “the Publisher”) and anyone involved in the creation, writing, or production of the companion disc, accompanying algorithms, code, or computer programs (“the software”), and any accompanying Web site or software of the Work, cannot and do not warrant the performance or results that might be obtained by using the contents of the Work. The author, developers, and the Publisher have used their best efforts to ensure the accuracy and functionality of the textual material and/ or programs contained in this package; we, however, make no warranty of any kind, express or implied, regarding the performance of these contents or programs. The Work is sold “as is” without warranty (except for defective materials used in manufacturing the book or due to faulty workmanship).

The author, developers, and the publisher of any accompanying content, and anyone involved in the composition, production, and manufacturing of this work will not be liable for damages of any kind arising out of the use of (or the inability to use) the algorithms, source code, computer programs, or textual material contained in this publication. This includes, but is not limited to, loss of revenue or profit, or other incidental, physical, or consequential damages arising out of the use of this Work.

The sole remedy in the event of a claim of any kind is expressly limited to replacement of the book and/or disc, and only at the discretion of the Publisher. The use of “implied warranty” and certain “exclusions” vary from state to state and might not apply to the purchaser of this product.

Companion files are also available for downloading by writing to [email protected].

MICROSOFT®Access® 2021Programming

Pocket Primer

Julitta Korol

Copyright ©2022 by Mercury Learning and Information LLC. All rights reserved.

This publication, portions of it, or any accompanying software may not be reproduced in any way, stored in a retrieval system of any type, or transmitted by any means, media, electronic display, or mechanical display, including, but not limited to, photocopy, recording, Internet postings, or scanning, without prior permission in writing from the publisher.

Publisher: David PallaiMercury Learning and Information 22841 Quicksilver Drive Dulles, VA 20166 [email protected] www.merclearning.com (800) 232-0223

J.Korol. Microsoft® Access 2021 Programming Pocket Primer. ISBN: 978-1-68392-889-8

The publisher recognizes and respects all marks used by companies, manufacturers, and developers as a means to distinguish their products. All brand names and product names mentioned in this book are trademarks or service marks of their respective companies. Any omission or misuse (of any kind) of service marks or trademarks, etc. is not an attempt to infringe on the property of others.

Library of Congress Control Number: 2022941645222324321    This book is printed on acid-free paper in the United States of America.

Our titles are available for adoption, license, or bulk purchase by institutions, corporations, etc. For additional information, please contact the Customer Service Dept. at 800-232-0223(toll free).

All of our titles are available in digital format at academiccourseware.com and other digital vendors. Companion files (figures and code listings) for this title are available by contacting [email protected]. The sole obligation of Mercury Learning and Information to the purchaser is to replace the disc, based on defective materials or faulty workmanship, but not based on the operation or functionality of the product.

CONTENTS

Acknowledgments

Introduction

Chapter 1    Getting Started with Access VBA

Understanding VBA Modules and Procedure Types

Writing Procedures in a Standard Module

Executing Your Procedures

Understanding Class Modules

Events, Event Properties, and Event Procedures

Why Use Events?

Walking Through an Event Procedure

Compiling Your Procedures

Placing a Database in a Trusted Location

Summary

Chapter 2    Getting to Know Visual Basic Editor (VBE)

Understanding the Project Explorer Window

Understanding the Properties Window

Understanding the Code Window

Other Windows in the VBE

Assigning a Name to the VBA Project

Renaming a Module

Syntax and Programming Assistance

List Properties/Methods

Parameter Info

List Constants

Quick Info

Complete Word

Indent/Outdent

Comment Block/Uncomment Block

Using the Object Browser

Using the VBA Object Library

Using the Immediate Window

Summary

Chapter 3    Access VBA Fundamentals

Introduction to Data Types

Understanding and Using Variables

Declaring Variables

Specifying the Data Type of a Variable

Using Type Declaration Characters

Assigning Values to Variables

Forcing Declaration of Variables

Understanding the Scope of Variables

Procedure-Level (Local) Variables

Module-Level Variables

Project-Level Variables

Understanding the Lifetime of Variables

Using Temporary Variables

Creating a Temporary Variable with a TempVars    Collection Object

Retrieving Names and Values of TempVar Objects

Using Temporary Global Variables in Expressions

Removing a Temporary Variable from a    TempVars Collection Object

Using Static Variables

Using Object Variables

Disposing of Object Variables

Finding a Variable Definition

Determining the Data Type of a Variable

Using Constants in VBA Procedures

Intrinsic Constants

Summary

Chapter 4    Access VBA Built-In and Custom Functions

Writing Function Procedures

Running Function Procedures

Data Types and Functions

Passing Arguments By Reference and By Value

Using Optional Arguments

Using the IsMissing Function

VBA Built-In Functions for User Interaction

Using the MsgBox Function

Returning Values from the MsgBox Function

Using the InputBox Function

Converting Data Types

Summary

Chapter 5    Adding Decisions to Your Access VBA Programs

Relational and Logical Operators

If. . .Then Statement

Multiline If. . .Then Statement

Decisions Based on More than One Condition

If. . .Then. . .Else Statement

If. . .Then. . .ElseIf Statement

Nested If. . .Then Statements

Select Case Statement

Using Is with the Case Clause

Specifying a Range of Values in a Case Clause

Specifying Multiple Expressions in a Case Clause

Summary

Chapter 6    Adding Repeating Actions to Your Access VBA Programs

Using the Do. . .While Statement

Another Approach to the Do. . .While Statement

Using the Do. . .Until Statement

Another Approach to the Do. . .Until Statement

Using the For. . .Next Statement

Using the For Each. . .Next Statement

Exiting Loops Early

Nested Loops

Summary

Chapter 7    Keeping Track of Multiple Values Using Arrays

Understanding Arrays

Declaring Arrays

Array Upper and Lower Bounds

Initializing and Filling an Array

Filling an Array Using Individual Assignment Statements

Filling an Array Using the Array Function

Filling an Array Using the For. . .Next Loop

Using a One-Dimensional Array

Arrays and Looping Statements

Using a Two-Dimensional Array

Static and Dynamic Arrays

Array Functions

The Array Function

The IsArray Function

The Erase Function

The LBound and UBound Functions

Errors in Arrays

Parameter Arrays

Passing Arrays to Function Procedures

Sorting an Array

Summary

Chapter 8    Keeping Track of Multiple Values Using Collections

Creating Your Own Collection

Adding Items to Your Collection

Determine the Number of Items in Your Collection

Accessing Items in a Collection

Removing Items from a Collection

Updating Items in a Collection

Returning a Collection from a Function

Collections vs. Arrays

Watching the Execution of Your VBA Procedures

Summary

Chapter 9    Getting to Know Built-In Tools for Testing and Debugging

Syntax, Runtime, and Logic Errors

Stopping a Procedure

Using Breakpoints

Removing Breakpoints

Using the Immediate Window in Break Mode

Using the Stop Statement

Using the Assert Statement

Using the Add Watch Window

Removing Watch Expressions

Using Quick Watch

Using the Locals Window

Using the Call Stack Dialog Box

Stepping Through VBA Procedures

Stepping Over a Procedure

Stepping Out of a Procedure

Running a Procedure to Cursor

Setting the Next Statement

Showing the Next Statement

Navigating with Bookmarks

Stopping and Resetting VBA Procedures

Trapping Errors

Using the Err Object

Procedure Testing

Setting Error-Trapping Options

Summary

Index

Acknowledgments

As years pass and we gain more and more knowledge on a particular subject there is a tendency to publish books for people who want to know it all. But the truth is that we really don’t have time to read all the printed pages. I thank my publisher, David Pallai, for suggesting that I continue creating a smaller book that will serve as a starting point for anyone attempting to get into VBA programming in Access. I hope that you as a reader of this primer book will appreciate this short book and find that the knowledge gained from its pages will not only allow you to continue your programming journey, but also take you places you never thought possible.

I’m also thankful to Jennifer Blaney for her expert management of this book project. I owe a heartfelt thanks to my copyeditor for the thorough review of the manuscript and to the compositor for all the typesetting efforts that gave this book the easy-to-follow look and feel.

Julitta KorolLong Island, New YorkJune 2022

Introduction

I’ve been working with Access since the very beginning. Database concepts were completely new to me, but the Access interface made it a pleasure to work with almost daily. Step by step I acquired the skills of database management and then programming. I learned the latter by trial and error. When the first consulting opportunity came up to use my Access skills, I found that I barely knew enough to get started. But challenges do not scare me. I was eager to learn on the job. My first Access programming project was designing a custom quotation system for an automotive manufacturer. Despite my limited prior exposure to the programming concepts, I was able to deliver a system that automated a big chunk of work for that company. How was I able to do this? I find reading and doing is the first step towards mastering a skill like programming. This book presents enough programming concepts to get you started tackling your own Access database challenges. This is not a book about using Access. I assume you are already familiar with most tasks that you can achieve using Access built-in commands. But if you are ready to look beyond the standard user interface, you have come to the right place and have made a decision that will bring a whole set of new possibilities to Access. So, let’s forget the menus for now. Do your own thing. Automating Access is something everyone can do. With the right training, that is. This book’s purpose is to introduce you to Access built-in language, known as Visual Basic for Applications (VBA). With VBA you can begin delegating repetitive tasks to Access while freeing your time for projects that are more fun to do. Besides, knowing how to program these days is a lucrative skill. It will get you a secure, well-paying job.

This book was designed for someone like you who needs to master Access programming fundamentals without spending too much time. Most of the time all you need is a short book to get you started. It’s less overwhelming to deal with a new subject in smaller chunks. The VBA Programming Pocket Primer series will show you only the things you need to know to feel at home with VBA. What you learn in this book on Access programming will apply to, say, Excel programming. Just see my other book, the Microsoft Excel 2021 Programming Pocket Primer, to see what I mean. How’s that for knowledge transfer? Learn in Access and use it in Excel or other Microsoft Office applications. I call this sweet learning.

If you are looking for in-depth knowledge of Access programming (and have time to read through a 1,000-page book), then go ahead and try some of my thicker books available from Mercury Learning and Information.

Access is about doing, and so is this book. So do not try to read it while not at the computer. You can sit, stand, or lie down; it does not matter. But you do need to work with this book. Do the examples, read the comments. Do this until it becomes easy to do without the step-by-step instructions. Do not skip anything as the concepts in later chapters build on material introduced earlier.

CHAPTER OVERVIEW

Before you get started, allow me to give you a short overview of the things you’ll be learning as you progress through this primer book. Microsoft Access 2021 Programming Pocket Primer is divided into nine chapters that progressively introduce you to programming Microsoft Access.

Chapter 1Getting Started with Access VBA   In this chapter you learn about the types of Access procedures you can write and learn how and where they are written.

Chapter 2 Getting to Know Visual Basic Editor (VBE)   In this chapter you learn almost everything you need to know about working with the Visual Basic Editor window, commonly referred to as VBE. Some of the programming tools that are not covered here are discussed and used in Chapter 9.

Chapter 3Access VBA Fundamentals   This chapter introduces basic VBA concepts that allow you to store various pieces of information for later use.

Chapter 4 Access VBA Built-In and Custom Functions   In this chapter you find out how to provide additional information to your procedures and functions before they are run.

Chapter 5Adding Decisions to Your Access VBA Programs   In this chapter you learn how to control your program flow with several different decision-making statements.

Chapter 6Adding Repeating Actions to Your Access VBA Programs   In this chapter you learn how to repeat the same actions in your code by using looping structures.

Chapter 7Keeping Track of Multiple Values Using Arrays   In this chapter you learn about static and dynamic arrays and how to use them for holding various values.

Chapter 8 Keeping Track of Multiple Values Using Collections   In this chapter you learn how you can maintain your items of data while your program is running by using a special type of object – the collection.

Chapter 9 Getting to Know Built-In Tools for Testing and Debugging   In this chapter you begin using built-in debugging tools to test your programming code. You also learn how to add effective error-handling code to your procedures.

These nine chapters will give you the fundamental techniques and concepts you will need in order to continue your Access VBA learning path. If you feel comfortable using this type of instruction, I recommend my Access 2021/Microsoft 365 Programming by Example book that builds on these primer topics.

THE COMPANION FILES

The example files for all the hands-on activities in this book are available in the companion files. They may also be downloaded by contacting the publisher at [email protected]. Digital versions of this title are available at academiccourseware.com and other digital vendors.

C h a p t e r   1

Getting Startedwith Access VBA

Visual Basic for Applications (VBA) is the programming language built into all Microsoft® 365 applications, including Access®. In this chapter you acquire the fundamentals of VBA that you will use over and over again in building real-life Access database applications.

WRITING PROCEDURES IN A STANDARD MODULE

As mentioned earlier, procedures are created and stored in modules. Access has two types of modules: standard module and class module. Standard modules are used to hold subprocedures and function procedures that can be run from anywhere in the application because they are not associated with any form or report.

   Because we already have a couple of procedures to try out, let’s do a quick hands-on exercise to learn how to open standard modules, write procedures, and execute them.

NOTE

All code files and figures for the hands-on projects may be found in the companion files.

   Hands-On 1.1 Working in a Standard Module

Create the C:\VBAAccess2021_ByExample_Primer folder on your computer.

Open Access and click Blank database. Type Chap01 in the File Name box and click the folder button to set the location for the database to the C:\VBAAccess2021_ByExample_Primer folder. Finally, click the Create button to create the specified database (see Figure 1.1). Access will create the database in its default .ACCDB format.

Figure 1.1

Creating a blank desktop Access database.

To launch the programming environment, select the Database Tools tab and click Visual Basic (see Figure 1.2). You can also press Alt+F11 to get to this screen.

Figure 1.2

Activating a Visual Basic development environment.

The screen that opens is your Visual Basic Environment, often referred to as VBE. All your coding will be performed in this screen. Before you can do your work here, you need to determine which module you need to work with. As mentioned earlier, we use a standard module for most general programming tasks. Initially nothing is open, so let’s add the first module.

Insert a standard module by choosing Module from the Insert menu (see Figure 1.3).

Figure 1.3

Inserting a standard module.

Each module begins with a declaration section that lists various settings and declarations that apply to every procedure in the module. Figure 1.4 shows the default declaration. Option Compare Database specifies how string comparisons are evaluated in the module—whether the comparison is case-sensitive or insensitive. This is a case-insensitive comparison that respects the sort order of the database. This means that “a” is the same as “A.” If you delete the Option Compare Database statement, the default string comparison setting for the module is Option Compare Binary (used for case-sensitive comparisons where “a” is not the same as “A”).

Figure 1.4

Standard module.

Another declaration (not shown here) called the Option Explicit statement is often used to ensure that all variables used within this module are formally declared. You will learn about this statement and variables in Chapter 4.

   Following the declaration section is the procedure section, which holds the module’s procedures. You can begin writing your procedures at the cursor position within the Module1 (Code) window.

In the Module1 (Code) window, enter the code of subroutines and function procedures as shown in Figure 1.5. These are the same sub procedures and functions that we’ve discussed so far in this chapter. You can write procedures and functions in the same module, or you can keep them separate by adding another standard module to your VBA project.

   Notice that Access inserts a horizontal line after each End Sub or End Function keyword to make it easier to identify each procedure. The Procedure drop-down box at the top-right corner of the Module1 (Code) window displays the name of the procedure in which the insertion point is currently located.

Figure 1.5

Standard module with subprocedures and functions.

EXECUTING YOUR PROCEDURES

Now that you’ve filled the standard module with some procedures and functions, let’s see how you can run them. There are many ways of running (executing) your code. In the next hands-on exercise, you will execute your code in four different ways using:

Run menu (Run Sub/UserForm)

Toolbar button (Run Sub/UserForm)

Keyboard (F5)

Immediate window

   Hands-On 1.2   Running Procedures and Functions

Place the insertion point anywhere within the ShowMessage procedure. The Procedure box in the top-right corner of the Module1 (Code) window should display ShowMessage. Choose Run Sub/UserForm from the Run menu.

Access runs the selected procedure and displays the message box with the text “This is a message box in VBA.”

Click OK to close the message box. Try running this procedure again, this time by pressing the F5 key on the keyboard. Click OK to close the message box. If the Access window seems stuck and you can’t activate any menu option, this is often an indication that there is a message box open in the background. Access will not permit you to do any operation until you close the pop-up window.

Run this procedure for the third time by clicking the Run Sub/UserForm button () on the toolbar. This button has the same tooltip as the Run Sub/UserForm (F5) option on the Run menu.

NOTE

Procedures that require arguments cannot be executed directly using the methods you just learned. You need to type some input values for these procedures to run. A perfect place to do this is the Immediate window, which is covered in detail in Chapter 2, “Getting to Know Visual Basic Editor (VBE).” For now, let’s open this window and see how you can use it to run VBA procedures.

Select Immediate Window from the View menu.

Access opens a small window and places it just below the Module1 (Code) window. You can size and reposition this window as needed. Figure 1.6 shows statements that you will run from the Immediate window in Steps 5−8.

Type the following in the Immediate window and press Enter to execute.

ShowMessage2 "I'm learning VBA."

Access executes the procedure and displays the message in a message box. Click OK to close the message box. Notice that to execute the ShowMessage2 procedure, you need to type the procedure name, a space, and the text you want to display. The text string must be surrounded by double quotation marks. In a similar way you can execute the ShowMessage3 procedure by providing two required text strings. For example, on a new line in the Immediate window, type the following statement and press Enter to execute:

ShowMessage3 "Keep on learning.", "John"

   When you press the Enter key, Access executes the ShowMessage3 procedure and displays the text “John, your message is: Keep on learning.” Click OK to close this message box.

NOTE

You can also use the Call statement to run a procedure in the Immediate window. When using this statement, you must place the values of arguments within parentheses, as shown here:

Call ShowMessage3("Keep on learning.", "John")

Function procedures are executed using different methods. Step 6 demonstrates how to call the addTwoNumbers function.

On a new line in the Immediate window, type a question mark followed by the name of the function procedure and press Enter:

?addTwoNumbers

Access should display the result of this function (the number 5) on the next line in the Immediate window.

Now run the addTwoNumbers2 procedure. Type the following instruction in the Immediate window and press Enter:

?addTwoNumbers2(56, 24)

Access displays the result of adding these two numbers on the next line.

If you’d rather see the function result in a message box, type the following instruction in the Immediate window and press Enter:

MsgBox("Total=" & addTwoNumbers2(34,80))

Access displays a message box with the text “Total=114”.

NOTE

See Chapter 2 for more information on running your procedures and functions from the Immediate window.

Figure 1.6

Running procedures and functions in the Immediate window.

Now that you’ve familiarized yourself a bit with standard modules, let’s move on to another type of module known as the class module.

UNDERSTANDING CLASS MODULES

Class modules come in three varieties: standalone class modules, form modules, and report modules.

Standalone class modules—These modules are used to create your own custom objects with their own properties and methods. You create a standalone class module by choosing Insert | Class Module in the Microsoft Visual Basic for Applications window. Access will create a default class module named Class1 and will list it in the Class modules folder in the Project Explorer window. Standalone class modules are an advanced feature of VBA and are not covered in this primer book.

Form modules—Each Access form can contain a form module, which is a special type of a class module.

Report modules—Each Access report can contain a report module, which is a special type of class module.

All newly created forms and reports are lightweight by design because they don’t have modules associated with them when they’re first created. Therefore, they load and display faster than forms and reports with modules. These lightweight forms and reports have their Has Module property set to No (see Figure 1.7). When you open a form or report in Design view and click the View Code button ( ) in the Tools section of the Form Design or Report Design tab, Access creates a form or report module. The Has Module property of a form or report is automatically set to Yes to indicate that the form or report now has a module associated with it. Note that this happens even if you have not written a single line of VBA code. Access opens a module window and assigns a name to the module that consists of three parts: the name of the object (e.g., form or report), an underscore character, and the name of the form or report. For example, a newly created form that has not been saved is named Form_Form1, a form module in the Customers form is named Form_Customers, and a report module in the Customers report is named Report_Customers (see Figure 1.8).

As with report modules, form modules store event procedures for events recognized by the form and its controls, as well as general function procedures and subprocedures. You can also write Property Get, Property Let, and Property Set procedures to create custom properties for the form or report. As mentioned earlier these types of property procedures are beyond the scope of this primer book.

Figure 1.7

When you begin designing a new form in the Access user interface, the form does not have a module associated with it. Notice that the Has Module property on the form’s property sheet is set to No.

Figure 1.8

Database modules are automatically organized in folders. Form and report modules are listed in the Microsoft Access Class Objects folder. Standard modules can be found in the Modules folder. The Class Modules folder organizes standalone class modules.

EVENTS, EVENT PROPERTIES, AND EVENT PROCEDURES

To customize your database applications or to deliver products that fit your users’ specific needs, you’ll be doing quite a bit of event-driven programming. Access is an event-driven application. This means that whatever happens in an Access application is the result of an event that Access has detected. Events are things that happen to objects and can be triggered by the user or by the system, such as clicking a mouse button, pressing a key, selecting an item from a list, or changing a list of items available in a listbox. As a programmer, you will often want to modify the application’s built-in response to a particular event. Before the application processes the user’s mouseclicks and keypresses in the usual way, you can tell the application how to react to the activity. For example, if a user clicks a Delete button on your form, you can display a custom delete confirmation message to ensure that the user selected the intended record for deletion.

   For each event defined for a form, form control, or report, there is a corresponding event property. If you open any Access form in Design view and choose Properties in the Tools section of the Form Design tab, and then click the Event tab of the property sheet, you will see a long list of events your form can respond to (see Figure 1.9).

   Forms, reports, and the controls that appear on them have various event properties you can use to trigger desired actions. For example, you can open or close a form when a user clicks a command button, or you can enable or disable controls when the form loads.

To specify how a form, report, or control should respond to events, you can write event procedures. In your programming code, you may need to describe what should happen if a user clicks on a command button or selects from a combo box. For example, when you design a custom form, you should anticipate and program events that can occur at runtime (while the form is being used). The most common event is the Click event. Every time a command button is clicked, it triggers an event procedure to respond to the Click event for that button.

When you assign your event procedure to an event property, you set an event trap. Event trapping gives you considerable control in handling events because you basically interrupt the default processing that Access would normally carry out in response to the user’s keypress or mouseclick. If a user clicks a command button to save a form, whatever code you’ve written in the Click event of that command button will run. The event programming code is stored as a part of a form, report, or control and is triggered only when user interaction with a form or report generates a specific event; therefore, it cannot be used as a standalone procedure.

Figure 1.9

Event properties for an Access form are listed on the Event tab in the property sheet.

Why Use Events?

Events allow you to make your applications dynamic and interactive. To handle a specific event, you need to select the appropriate event property on the property sheet and then write an event handling procedure. Access will provide its own default response to those events you have not programmed. Events cannot be defined for tables or queries.

Walking Through an Event Procedure

The following hands-on exercise demonstrates how to write event procedures. Your task is to change the background color of a text box control on a form when the text box is selected and then return the default background color when you tab or click out of that text box.

   Hands-On 1.3   Writing an Event Procedure

Close the Chap01.accdb database file used in Hands-On 1.1 and save changes to the file when prompted.

Copy the AssetTracking.accdb database from the companion files to your C:\VBAAccess2021_ByExample_Primer folder. This file is a copy of the Asset tracking database template provided by Microsoft.

Open the AssetTracking.accdb database. Upon loading, when you see a Welcome screen, click the Get Started button.

Access opens the database and displays a security warning message (see Figure 1.10). To use the file, click the Enable Content button in the message bar. Access will close the database and reopen it. If you see the Welcome screen, click the Get Started button again.

NOTE

The last section of this chapter explains how you can use trusted locations to keep Access from disabling the VBA code upon opening a database.

   As Microsoft continues to improve security in Office, the default behavior and banners displayed in Access and other Office applications may be different from those presented in the instructions and images included in this book. For the most recent guidelines, please see https://docs.microsoft.com/en-us/deployoffice/security/internet-macros-blocked.

Open the Asset Details form in Design view. To do this, right-click the Asset Details form and choose Design View from the shortcut menu.

NOTE

If the property sheet is not displayed next to the AssetDetails form, click the Property Sheet button in the Tools group of the Ribbon’s Form Design tab.

Click the Manufacturer text box control on the Asset Details form, and then click the Event tab in the property sheet. The property sheet will display Manufacturer in the control drop-down box.

   The list of event procedures available for the text box control appears, as shown in Figure 1.11.

Figure 1.10

Active content such as VBA Macros can contain viruses and other security hazards. By default, Access displays a Security Warning message when you first load a database file that contains active content. You should enable content only if you trust the contents of the file.

Figure 1.11