You are on page 1of 40

PR

EV

IE

W

Access 2007:
VBA Programming
Instructor’s Edition

NOT FOR PRINTING OR INSTRUCTIONAL USE

W

Access 2007: VBA Programming
Charles G. Blum and Adam A. Wilcox

Writer:

Don Tremblay

Developmental Editor:

Steve English

Copyeditor:

Ken Maher

Keytester:

Cliff Coryea

Series Designer:

Adam A. Wilcox

COPYRIGHT © 2007 Axzo Press

IE

Series Product Managers:

ALL RIGHTS RESERVED. No part of this work may be reproduced, transcribed, or used in any form or by any
means⎯graphic, electronic, or mechanical, including photocopying, recording, taping, Web distribution, or
information storage and retrieval systems⎯without the prior written permission of the publisher.
For more information, go to www.axzopress.com.

Trademarks

EV

ILT Series is a trademark of Axzo Press.

Some of the product names and company names used in this book have been used for identification purposes only and
may be trademarks or registered trademarks of their respective manufacturers and sellers.

Disclaimer

We reserve the right to revise this publication and make changes from time to time in its content
without notice.
ISBN 10: 1-4239-5102-6
ISBN 13: 978-1-4239-5102-5

Printed in the United States of America

PR

1 2 3 4 5 GLOB 06 05 04 03

NOT FOR PRINTING OR INSTRUCTIONAL USE

Introduction
Topic A:
Topic B:
Topic C:
Topic D:

W

Contents
iii

About the manual............................................................................... iv
Setting student expectations .............................................................. ix
Classroom setup.................................................................................xii
Support.............................................................................................. xvi

Visual Basic Editor

1-1

IE

Topic A: Objects .............................................................................................. 1-2
Topic B: Object Browser ................................................................................ 1-13
Topic C: Collections ....................................................................................... 1-18
Unit summary: Visual Basic Editor................................................................. 1-21

Programming basics

2-1

Topic A: Working with data ............................................................................ 2-2
Topic B: Scope ............................................................................................... 2-12
Unit summary: Programming basics ............................................................... 2-26

Control structures

3-1

EV

Topic A: Decision structures............................................................................ 3-2
Topic B: Loop structures ................................................................................ 3-10
Unit summary: Control structures ................................................................... 3-19

ActiveX Data Objects

4-1

Topic A: Getting started with ActiveX Data Objects ...................................... 4-2
Topic B: Working with ActiveX Data Objects................................................ 4-6
Unit summary: ActiveX Data Objects............................................................. 4-19

VBA debugging tools

5-1

PR

Topic A: Errors in code.................................................................................... 5-2
Topic B: Debugging techniques ...................................................................... 5-4
Topic C: Handling runtime errors................................................................... 5-20
Unit summary: VBA debugging tools............................................................. 5-23

Office integration

A-1

Topic A: Automating Office 2007 ...................................................................A-2
Topic B: Working with Word from Access.....................................................A-3
Topic C: Working with Excel from Access.....................................................A-5

Course summary

S-1

Topic A: Course summary ............................................................................... S-2
Topic B: Continued learning after class .......................................................... S-4

Quick reference

Q-1

Glossary

G-1

Index

I-1

NOT FOR PRINTING OR INSTRUCTIONAL USE

Access 2007: VBA Programming

PR

EV

IE

W

ii

NOT FOR PRINTING OR INSTRUCTIONAL USE

iii W Introduction After reading this introduction. you’ll know how to: IE A Use ILT Series training manuals in general. B Use prerequisites. EV C Set up a classroom to teach this course. NOT FOR PRINTING OR INSTRUCTIONAL USE . D Get support for setting up and teaching this PR course. a target student description. course objectives. and a skills inventory to set students’ expectations properly for the course.

It contains target student. having a thinking. Leading the students through these activities will teach the skills and concepts effectively. For many students. objective. our training manuals facilitate students’ learning by providing structured interaction with the software itself. as successful as possible. and conventions. then teaching.iv Access 2007: VBA Programming ILT Series philosophy W Topic A: About the manual Our goal is to make you. To that end. We also provide overall course objectives and a course summary to provide both an introduction to and closure on the entire course. While we provide text to help you explain difficult concepts. prerequisite. Table of contents The table of contents acts as a learning roadmap for you and the students. For this reason. Because the students’ focus should be on you. IE We believe strongly in the instructor-led classroom. lessons begin with objectives and end with summaries. features. and providing summary and review afterwards. the instructor. We encourage your feedback in helping us to improve our manuals continually to meet your needs. Introduction The introduction contains information about our training philosophy and our manual components. our manuals are designed and written to facilitate your interaction with the students and not to call attention to manuals themselves. Our goal is your success. We believe in the basic approach of setting expectations. the introduction contains support information. and setup information for the specific course. the hands-on activities are the focus of our courses. EV Manual components This manual contains these major components: • Table of contents • Introduction • Units • Appendix • Course summary • Quick reference • Glossary • Index PR Each element is described below. feeling instructor in front of them is always the most comfortable way to learn. NOT FOR PRINTING OR INSTRUCTIONAL USE . Finally.

feature. a summary. one telling students what to do. NOT FOR PRINTING OR INSTRUCTIONAL USE . Throughout a unit. Appendices IE An appendix is similar to a unit in that it contains objectives and conceptual explanations. Units conclude with a summary comprising one paragraph for each topic. or concept. within the unit. descriptions. Quick reference The quick reference is an at-a-glance job aid summarizing some of the more common features of the software. an appendix doesn’t include hands-on activities. Index PR The index at the end of this manual makes it easy for you and your students to find information about a particular software component. the other providing explanations. instructor notes are found in the left margin. or an independent practice activity. and lists additional resources students might find useful as they continue to learn about the software. A unit begins with a title page that lists objectives for each major subdivision. The conceptual information takes the form of text paragraphs. However. The course summary also indicates the next course in this series. and an independent practice activity that gives students an opportunity to practice the skills they’ve learned. and graphics. conceptual and explanatory information alternates with hands-on activities. Course summary EV This section provides a text summary of the entire course. exhibits. Within each topic. and tables.Introduction v Units W Units are the largest structural component of the actual course content. The activities are structured in two columns. It’s useful for providing closure at the end of the course. if there is one. lists. or topic. Glossary The glossary provides definitions for all of the key terms used in this course.

any code that’s too long to fit on a single line is divided into segments by one or more continuation characters (►). Tips give extra information the instructor can share with students. Code font Indicates code or syntax. Warning icon. In the left column of hands-on activities. IE Instructor note/icon W We’ve tried to keep the number of elements and the types of formatting to a minimum in the manuals. and warnings for the instructor. bold sans-serif text indicates an explicit item that you select. EV Select bold item Keycaps like e Indicate a key on the keyboard you must press. Setup notes provide a realistic business context for instructors to share with students. indicates an explicit item that you select. Longer strings of ► code will look ► like this. hints. In the hands-on activities. But there are some conventions and icons you should know about. indicates a new term or feature. This code should be entered as a continuous string of text. In the left margin. provide tips. Tip icon. or type. Instructor notes. choose. PR Projector icon. or type. indicates a key term or concept. Warnings prepare instructors for potential classroom management problems. or indicate additional setup steps required for the current activity. NOT FOR PRINTING OR INSTRUCTIONAL USE . We think this aids in clarity and makes the manuals more elegant looking. Bold text In unit summaries. Projector notes indicate that there is a PowerPoint slide for the adjacent content. In an independent practice activity. choose. Setup icon.vi Access 2007: VBA Programming Manual conventions Convention Description Italic text In conceptual text.

setups. it may not be practical to rename the data file. As students work through the activities. To the left. The “Here’s how” column gives short directions to the students. students are using a file called “Sales” for the first time. therefore. IE Take the time to make sure your students understand this worksheet. Of course. want to re-key the activity starting from scratch. however. they save the file as “My sales. and other information for the instructor only. for example.Introduction vii Hands-on activities Do it! A-1: Creating a commission formula Here’s how 1 Open Sales Here’s why This is an oversimplified sales compensation worksheet. We’ll be here a while. graphics. W The hands-on activities are the most important parts of our manuals. If students want to retry one of these activities. Here’s a sample: 2 Observe the contents of cell F4 The commission rate formulas use the name “C_Rate” instead of a value for the commission rate. EV For these activities. The “Here’s why” column provides explanations. they modify and update these files.” thus leaving the “Sales” file unchanged. To make it easy to start over. instructor notes provide tips. Such exceptions are indicated with an instructor note. warnings. At the end of this activity. students rename each data file at the end of the first activity in which the file is modified. they can start over using the original “Sales” file. you need to provide a fresh copy of the original data file. Our convention for renaming files is to add the word “My” to the beginning of the file name. they might make a mistake and. PR In some activities. If students make mistakes. commissions. and clarifications. NOT FOR PRINTING OR INSTRUCTIONAL USE . They’re divided into two primary columns. It shows sales totals. we’ve provided a collection of data files designed to help students learn each skill in a real-world business context. and incentives for five sales reps. In the above activity.

a new toolbar will be available at the top of the PowerPoint window. 2 Start PowerPoint. A copy of PowerPoint Viewer is included. We strongly recommend that you run these presentations from the instructor’s station as you teach this course. or to play it again.txt) and Excel (. By default. and rewind the movie. You can use this panel to start. The Course_ILT add-in should now appear in the Available Add-Ins list (in the Add-Ins dialog box).ppa file. PR When you run a presentation and come to a slide that contains a Flash movie. A message box appears. warning you that macros can contain viruses. Macro.viii Access 2007: VBA Programming PowerPoint presentations The ILT Series PowerPoint add-in W Each unit in this course has an accompanying PowerPoint presentation. Each one begins with a list of unit objectives and ends with a unit summary slide. you’re prompted to save the presentation to your hard drive and try again. Security to open the Security dialog box. select Medium (if necessary).xls) format. 6 Click Enable Macros. and then click OK. so it isn’t necessary to have PowerPoint installed on your computer. 3 Choose Tools. The “x” in front of Course_ILT indicates that the add-in is loaded. After you complete this procedure. 7 Click Close to close the Add-Ins dialog box. 4 Choose Tools. click Add New. stop. These slide shows are designed to support your classroom instruction while providing students with a visual focus. NOT FOR PRINTING OR INSTRUCTIONAL USE .” Click this button to generate slide notes files in both text (. This toolbar contains a single button labeled “Create SlideNotes. 5 Browse to and select the Course_ILT. Add-Ins to open the Add-Ins dialog box. If the PowerPoint file is on a CD-ROM or in some other location to which the SlideNotes files can’t be saved. and then click OK. Then. you see a small control panel in the lower-left corner of the screen.ppa file to a convenient location on your hard drive. The CD also contains a PowerPoint add-in that enables you to do two things: • Create slide notes for the class • Display a control panel for the Flash movies embedded in the presentations EV IE To load the PowerPoint add-in: 1 Copy the Course_ILT. these files are saved to the folder that contains the presentation. On the Security Level tab.

and write error-handling code. and implementing ActiveX Data Objects. This topic will help you do that by providing: • Prerequisites for this course • A description of the target student at whom the course is aimed • A list of the objectives for the course • A skills assessment for the course Course prerequisites IE Students taking this course should be familiar with personal computers and the use of a keyboard and a mouse. this course assumes that students have completed the following courses or have equivalent experience: • Windows XP: Basic or Windows Vista: Basic • Access 2007: Application Development Target student EV The target student for this course should be familiar with Access 2007 and Visual Basic for Applications. and logical errors. use Object Browser. Students get the most out of this course. combine data by using expressions. After completing this course. and call one procedure from another. and use the Controls collection. Students should be able to use various VBA programming elements. identify collection objects. Furthermore. NOT FOR PRINTING OR INSTRUCTIONAL USE .Introduction ix Topic B: Setting student expectations W Properly setting students’ expectations is essential to your success. • Identify ActiveX Data Objects (ADO) architecture and collections. • Identify compile-time. connect to a database. if their goal is to become proficient in working with objects and collections. get user input. This approach gives the students an idea about what to expect and also helps you identify students who might be misplaced. and create a parameter query. work with a Recordset. • Use decision structures and use loop structures. Course objectives You should share these overall course objectives with your students at the beginning of the day. create Sub and Function procedures. students will know how to: • Work with objects. run-time. use the debugging tools. Students are considered misplaced when they lack the prerequisite knowledge or when they already know most of the subject matter to be covered. PR • Manipulate data by declaring variables.

he or she might not be ready for the class. and If…Then…ElseIf statements Use the Select Case statement Use the For…Next. For Each…Next.x Access 2007: VBA Programming Skills inventory W Use the following form to gauge students’ skill level entering the class (students have copies in the introductions of their student manuals). and Do While…Loop loops Discuss ADO and ADO collections PR Connect to a database Create a Recordset object Navigate a Recordset Add records to a Recordset Modify a record Cancel changes to a record Delete a record Create a parameter query NOT FOR PRINTING OR INSTRUCTIONAL USE . For each skill listed. their properties. If…Then…Else. with 5 being the most familiar. on the other hand. and public-level scopes Create and call a Sub procedure Create and call a Function procedure Use If…Then. module-. methods. might need to move on to the next course in the series. A student who seems to understand all of the skills. it’s intended to provide students with an idea of where they’re starting from at the beginning of class. and events IE Use the Object Browser Identify collection objects Use the Controls collection Examine data types and variables Use operators and interaction functions EV Observe modules and procedures Examine procedure-. If a student is wholly unfamiliar with all the skills. Skill 1 2 3 4 5 Work with objects. Rather. have students rate their familiarity from 1 to 5. Emphasize that this isn’t a test.

xi Introduction Skill 1 2 3 4 5 Discuss debugging tools Set a breakpoint W Discuss types of errors Add and delete a watch expression Use Step Into Work with the Immediate window IE Use the Locals window PR EV Write error-handling code NOT FOR PRINTING OR INSTRUCTIONAL USE .

setup information for the first time you teach the class. and setup information for each time that you teach after the first time you set up the classroom. or higher resolution monitor Software requirements You need the following software: • Windows XP. The setup process described here may vary slightly from what you encounter. Windows Vista. Our hands-on approach to learning requires that they do.microsoft. It includes minimum requirements for the students’ personal computers.com – Downloading the Student Data files (if necessary) NOT FOR PRINTING OR INSTRUCTIONAL USE .xii Access 2007: VBA Programming Topic C: Classroom setup W All our courses assume that each student has a personal computer to use during the class. or Windows Server 2003 • Microsoft Office 2007 Network requirements The following network components and connectivity are also required for this course: PR • Internet access. IE The Windows operating system and the Microsoft Office 2007 suite are subject to continual updating by Microsoft. The versions of each that you install are by definition different from the versions that we used to prepare this course in February 2007. This also applies to activities and screen shots throughout the course. for the following purposes: – Updating the Windows operating system and Microsoft Office 2007 at update. Hardware requirements Each student’s personal computer should have: • A keyboard and a mouse • Pentium 500 MHz processor (or higher) • 256 MB RAM (or higher) • 2 GB of available hard drive space EV • CD-ROM drive • SVGA at 1024 × 768. This topic gives information on how to set up the classroom to teach this course.

b Select the Customize installation option and click Next. activate the Downloads tab. e Set all but the following to Not Available: Access 2007.) a Click Start. and Office Tools.com. as follows: a When prompted for the CD key. but the screen shots in this course were taken using Windows XP. (If you installed Windows yourself. Update the operating system with the latest critical updates and service packs. then launch the Control Panel.” d Click OK to close the Internet Options dialog box. Note: You can also use Windows Vista or Windows Server 2003. Office Shared Features. asking you to make Internet Explorer your default browser.microsoft. and Office Tools. click Yes. Open Internet Explorer and navigate to update. enter the code included with your software. an e-mail account isn’t. Internet Explorer displays the Office Online Web site. h On the Office Online Web page.Introduction xiii First-time setup instructions W 1 Install Windows XP on an NTFS partition according to the software manufacturer’s instructions. Install Microsoft Office 2007 according to the software manufacturer’s instructions. Web access is required. f If a prompt appears. c Activate the Installation Options tab. verify that Internet Explorer is the default Web browser. open the Display Properties dialog box and apply the following settings: • Theme — Windows XP • Screen resolution — 1024 by 768 pixels EV IE 3 • Color quality — High (24 bit) or higher If Windows was already loaded on this PC. f Click Install Now. Internet Options. e Close and re-open Internet Explorer. click the dropdown arrow and choose Run all from My Computer. j Close Internet Explorer. so students’ screens will look somewhat different. g On the last screen of the Office 2007 installer. Internet Explorer. All Programs. 2 If the operating system is Windows XP. skip this step. c Check “Internet Explorer should check to see whether it is the default browser. i Download and install any available updates. g Close Internet Explorer. and the installer window closes. 4 5 PR 6 NOT FOR PRINTING OR INSTRUCTIONAL USE . Office Shared Features. b Choose Tools. d For Access 2007. click Go to Office Online. Create an Internet account for the student.

i Click OK to close the Trust Center dialog box. h Click OK to close the Microsoft Office 2007 Trusted Location dialog box. choose Popular. f Select “I don’t want to use Microsoft Update. verify that “Search Microsoft Office Online for Help content when I’m connected to the Internet” is checked. The Microsoft Office 2007 Trusted Location dialog box opens. 11 Make the student data folder the default file location. b Click the link for Microsoft Access 2007 to display a page of course listings. the Welcome to the 2007 Microsoft Office System dialog box appears. 9 Start Access 2007. You can download the data directly to student machines. NOT FOR PRINTING OR INSTRUCTIONAL USE . After activating. 8 Create a student data folder on each student’s computer. g Check Subfolders of this location are also trusted. to a central location on your own network. b On the Trust Center page. and navigate to the student data folder. download the Student Data files for the course.html. e Click Next. 10 To prevent students from receiving a security warning when they open files in Access 2007. e Close Access 2007. c Verify that “Download a file periodically that helps determine system problems” is cleared. click Trust Center Settings. a Activate the software. a In the left panel of the Access Options dialog box. d Verify that “Sign up for the Customer Experience Improvement Program” is cleared. c Navigate to the Trusted Locations page. d Click OK to close the Access Options dialog box. The Trust Center dialog box opens. b On the Privacy Options screen. c Click the link for downloading the Student Data files. d Click Add new location. or to a disk.” g Click Finish to close the dialog box. and copy the Student Data files to that folder. and then click the link for Access 2007: VBA Programming.xiv Access 2007: VBA Programming PR EV IE W 7 If you don’t have the data CD that came with this manual.com/instructor_tools. e Click Browse and navigate to the student data folder. and follow the instructions that appear on your screen.courseilt. f Click OK to close the Browse dialog box. c Click OK to close the Default Database Path dialog box. designate the student data folder as a Trusted Location: a Click the Office Button and choose Access Options to open the Access Options dialog box. a Connect to www. b Under Creating databases. click Browse.

1 Delete the contents of the Student Data folder. create a folder named Student Data at the root of the hard drive. NOT FOR PRINTING OR INSTRUCTIONAL USE .com.Introduction xv Setup instructions for every class PR EV IE W Every time you teach this course. if necessary.microsoft. (If this is the first time you’re teaching the course.) 3 Open Internet Explorer and navigate to update. (See the download instructions in the preceding section.) 2 Copy the data files to the Student Data folder. you need to perform the following steps to set up each student computer. Update the operating system and Office 2007.

including course outlines and answers to frequently asked questions. If you need help setting up this class or teaching a particular unit.com. click Instructor-Led Training and browse our subject categories.xvi Access 2007: VBA Programming Topic D: Support Contacting us W Your success is our primary concern. To download these files. or activity. Then. www.axzopress. Please contact us through our Web site. You will need to provide the name of the course. go to www. NOT FOR PRINTING OR INSTRUCTIONAL USE . topic. under Downloads. and be as specific as possible about the kind of help you need. please don’t hesitate to get in touch with us.com. Instructor’s tools PR EV IE Our Web site provides several instructor’s tools for each course.axzopress.

NOT FOR PRINTING OR INSTRUCTIONAL USE . B Use Object Browser to get information about objects.Unit 1 Visual Basic Editor W 1–1 Unit time: 65 minutes Complete this unit. and events. their properties. and you’ll know how to: IE A Work with objects. C Identify collection objects and use the PR EV Controls collection. methods.

and procedures. one object can contain other objects. a button is clicked. EV Each Office application has its own set of objects or object model. For instance. NOT FOR PRINTING OR INSTRUCTIONAL USE . some events occur when a form opens. and Access contains table and form objects. a form object contains controls. VBA is based on Object Oriented Programming (OOP). Object is a generic object type that VBA provides and Access provides Control as its generic object type. such as buttons and check boxes. data. is a programming language that comes as a part of the Microsoft Office suite and is shared among Office applications. queries. The details of OOP are outside the scope of this unit. You can access VBE through any Microsoft Office application. Objects constitute a way of organizing and relating variables. or VBA. and write code for the project. the Forms collection includes all currently open form objects. but a basic understanding is sufficient to start programming. Generic object types You can use Generic object types when you aren’t sure what type of object you want to work with. such as fields and indexes. For example. the applications themselves are also objects.1–2 Access 2007: VBA Programming Topic A: Objects Explanation You can decide to go further into OOP as time allows. IE An object has certain characteristics and behavior. You can write code that runs when an event occurs. Word contains document and paragraph objects. and test VBA code. edit. or a text box loses focus. Objects can be visible things. and forms in an Access application are themselves individual. or even entire applications. set properties. individual objects and collection objects. In Access and other Office applications. and text boxes. For example. For example. queries. Design time is when you design forms. These characteristics are the object’s properties and can be set at either design time or run time of a project. The VBE helps you manipulate object properties and methods. You can write VBA code to manipulate forms. Run time is when the project is executing. Both Access and VBA provide generic object types. command buttons. In VBA. all the elements of a program are considered objects. An application consists of two types of objects. A collection object is an arranged group of items that can be treated as a unit. An object’s method is a behavior or action that’s performed by the object and can be used to accomplish specific tasks. and a table object contains objects. such as reports. For example. Access objects PR Tables. An object can respond to events. For instance. Visual Basic Editor (VBE) is the environment in which you write. reports. place controls in the form. you can change text in a text box and also hide the text box by writing code in VBE. You can assign any type of object or control to this generic object type. Rename is a method that changes the name of an object. command buttons. For example. or more conceptual elements. such as forms. In OOP. and other controls. W Visual Basic for Applications.

methods. 5 What generic object types are available in VBA and Access? EV VBA provides the Object type and Access provides the Control type. and events? Answers will vary. 3 Is Access an object in VBA? If so. Properties: plugged in (a true/false property). because applications are also objects in VBA and can be programmed or manipulated. NOT FOR PRINTING OR INSTRUCTIONAL USE . lever manually popped up. In Access. pop toast up. Methods: toast bread. 6 Consider modeling a real-world object – a toaster. have students think of other simple objects to model and list the relevant properties. color. why? Yes. forms. What are its properties. why? IE Yes. PR If time allows. Access is an object.Visual Basic Editor Do it! A-1: 1–3 Discussing objects 1 What’s an object? W Questions and answers An object is an entity that has specific characteristics and behavior. number of slots. change toasting time. tables. size. 2 Is VBA shared among Office applications? If so. Events: lever pushed down. and controls are objects. 4 When do you use generic object types? You use generic object types when you aren’t sure what type of object or control you need to use. toasting time. VBA is shared by all Office applications because it’s part of the Microsoft Office suite. and events. methods. toasting time dial changed.

A procedure is a block of VBA program code that performs a specific task. such as Caption. and the current value of the properties. The two tabs in this window are Alphabetic and Categorized tabs. Property names Property values PR Exhibit 1-1: The Properties window NOT FOR PRINTING OR INSTRUCTIONAL USE . The Alphabetic tab displays the properties of the selected object alphabetically. Format. Event. properties. whereas the Categorized tab displays the properties for the selected object by category.1–4 Access 2007: VBA Programming Object properties You can modify properties and methods. The Properties window W Explanation EV Object box IE The Properties window displays the name of the object. You can also attach code to the events of an object to change its appearance. You can also use VBA objects to create procedures that perform more complex tasks than simply executing a set of recorded actions. its properties. as shown in Exhibit 1-1. such as Data. and the action it performs. and AutoCenter are in the Format category. and Other. BorderStyle. For example. behavior.

observe the Name property (If necessary. 7 In the Properties window. 1–5 6 In the Object box list in the Properties pane. display Forms If necessary.) It’s at the top of the list. PR 10 In the Properties window. Tell students to scroll to view the tasks. Format.Visual Basic Editor Do it! A-2: Examining the Properties window 1 Start Access 2 Open Objects Here’s why Choose Start. 9 Observe the Properties window The properties are categorized based on the tasks. Microsoft Office. 8 In the Properties window. 4 Open frmOrder in Design view (Right-click it and choose Design View. EV In the Properties window. Microsoft Office Access 2007. observe the Caption property of the form This is the name that appears on the object tab when the form is opened in Access. such as Data. activate the Alphabetic tab NOT FOR PRINTING OR INSTRUCTIONAL USE . All Programs.) You’ll examine the properties of this form. Event. 3 In the Navigation Pane. This is the name assigned to the form object.) To select the properties for the frmOrder form. 5 On the Design tab.) To open the Visual Basic Editor window. IE Help students navigate to the current unit folder. click (The View Code button is in the Tools group. To view the properties in alphabetical order. activate the Categorized tab To view the properties grouped according to the tasks they perform. The code windows for other forms are also displayed. and Other. select frmOrder (You can resize the pane to be able to see all the property names. Tell students to scroll down. W Here’s how From the current unit folder.

This list appears in the value column of the Properties window.) To switch to the Microsoft Access window.1–6 Access 2007: VBA Programming Changing properties Explanation You can change option properties.) The caption for the object tab is frmOrder. observe the Caption property IE Tell students that they might need to scroll up. such as 0-None or 2-sizable. 4 Switch back to the VBE window Click View Code. such as changing the caption of a form to reflect the data it contains. EV Tell students they can also right-click the form’s tab and choose Form view. Some properties have a list of predefined values from which you can select. 9 Update and close the form NOT FOR PRINTING OR INSTRUCTIONAL USE . Order Form Press e 7 Switch to Access PR Students can click the Access button in the VBE or on the taskbar. 2 Click (The View Microsoft Office Access button is on the Standard toolbar of the VBE window. Here’s why 3 Switch to Design view To return to the Design view of the form. Switch to Form view (The Form view button is on the status bar at the lower right of the Access window. 1 In the Properties window. A-3: Do it! Modifying the object properties Here’s how Students can also switch by clicking the relevant buttons on the task bar. W You change a property of an Access object by selecting the object and then editing the property value in the Properties window. 5 In the Properties window. 8 Switch to Form view The caption of the form reads Order Form. 6 Edit the Property value to read To change the caption to Order Form. The caption frmOrder appears as the property value. doubleclick Caption You’ll change the caption of the form. you can select a value for the BorderStyle property of a form. The object immediately reflects the change. For example.

You can add a new module in a project by choosing Insert. Module. the procedure associated with that event appears in the Code window. In such cases. For example. If you select an object from the Object list. Each object that appears in the Project Explorer window has a separate Code window associated with it. declarations. when you select Form from the Object list. the definition of the object’s default procedure appears in the Code window. To open the Code window. Standard modules contain procedures that are available to other procedures throughout your project. double-click a form or module in the Project Explorer window. It’s known as Form module. When you select an event from the Procedure list. Procedure list PR Object list Exhibit 1-2: A sample Code window NOT FOR PRINTING OR INSTRUCTIONAL USE . you don’t need to select the event from the Procedure list. Class modules contain the definition for a new object.Visual Basic Editor 1–7 Using the Code window You can control object properties by writing VBA code in the Code window. and procedures that are stored as a single unit and contains one or more related procedures. the Load event procedure for the form appears in the Code window by default. The Code window that includes the code for a specific form or its control is also a Standard module by itself. The two types of modules in Access are Standard modules and Class modules. A module includes statements. W Explanation EV IE The list box in the upper left corner of the Code window that lists the form and other objects in the form is called an Object list. such as the one shown in Exhibit 1-2. The list box in the upper right corner of the Code window that lists all the events for the object displayed in the Object list is called the Procedure list. The procedures defined in a Class module become the properties and method for the object.

property = value W In this syntax. property is the property name. to change the caption of the form named frmRetailer. you would enter the code: Form_frmRetailer. and value is the value you want to assign to the property. the Caption property of the form frmRetailer is set to Retailer Form. the Auto List option of VBA displays a list of object members. object represents the name of the object. NOT FOR PRINTING OR INSTRUCTIONAL USE . For example.Caption ="Retailer Form" PR EV IE In this example. When you type a period after an object name. The object name and the property name are separated by a period (. There are no spaces before or after the period. such as data type or property from which you can choose.).1–8 Access 2007: VBA Programming Following is the general syntax for setting object properties through code: object. This helps you to avoid incorrectly typing a name that isn’t a method or property of the specified object.

5 Press t To indent the code for better readability. 8 Close the form NOT FOR PRINTING OR INSTRUCTIONAL USE . 6 Type the following code: Form_frmRetailer. 2 Switch to VBE In the Design tab. click View Code. 1–9 3 In the Objects .) These lines of code appear automatically. select Form EV (You’ll write code to change the caption of the form. W Tell students to resize the Code window if necessary. which includes the objects associated with the form. PR Press t ="Retailer Form" 7 Switch to Access and to Form view Update the database The caption of the form reads Retailer Form. The Load event of a form occurs when the form is opened and its controls display.Form_frmRetailer window. Form_Load() is the name of the event procedure. 4 From the Object list.c An Auto List appears as soon as you type the period. In the first line. then when you press C the selection moves to items starting with that letter. The word Caption appears automatically in the code line. Type the following code: To change the form caption to Retailer Form.Visual Basic Editor Do it! A-4: Writing code to change object properties Here’s how Here’s why 1 Open frmRetailer in Design view You’ll change the caption of this form by using code. Click Save on the Quick Access toolbar. click as shown IE To display the Object list.

8 Click Yes To save the change and close the form. they’d have received the same prompt. 2 From the Object list. Type the following code: You can also press Tab after you type ac. which can have one of the following values: • acQuitPrompt: Displays a dialog box that prompts you to save the changes and then quits Microsoft Access. W The Quit method has a parameter. An Auto List appears. You can use this method to quit Microsoft Access. For example. 5 Switch to Form view Switch to Access then to Form view. with or without saving according to your answer.1–10 Access 2007: VBA Programming Using methods Explanation The actions of an object are defined by the methods attached to it. select You’ll apply the Quit method to the Close button. Quit is a method of the Application object. providing object classes and data types from which you can choose. You can also close the dialog box by clicking the Cancel button. NOT FOR PRINTING OR INSTRUCTIONAL USE . cmdClose 3 Press t EV Type the following code: Application. Quit acQuitPrompt PR 4 Close the Code window Tell students that. Click the Close Window button on the upper right corner of the Code window. then switch to its code window. prompting you to save changes. • acQuitSaveAll: Saves all objects and then quits Microsoft Access. if they tried to close Access. 7 Close the form A message box appears. • acQuitSaveNone: Quits Microsoft Access without saving the changes Using a method Here’s how Here’s why IE A-5: Do it! 1 Open the code window for frmOrder Open the form in Design view. 6 Edit the Quantity box to read 200 To provide a new quantity.

Events include user actions. The Activate event of a form occurs when the form becomes the active window. double-click the object to display the Code window. For example.Visual Basic Editor 1–11 Attaching code to events A procedure can run in response to a specific user action. You use event procedures to associate code with an event. the code executes when the event occurs. You do this by associating the code to an object event. double-clicks. and opening or closing of forms. NOT FOR PRINTING OR INSTRUCTIONAL USE . W Explanation When you associate code with an event. select an event from the Procedure list. such as mouse clicks. such as clicking a button. PR EV IE To program an event. The events for the object selected in the Object list are listed in the Procedure list. Then. such as when another action triggers the event. select the object. and enter the code you want. you can write code for a form’s Activate event to display a message informing you that you can’t change the data in the form when a user activates it.

From the Procedure list. 4 Press t and type the following code: MsgBox The Auto Quick Info feature appears. select Form 3 Click as shown W 1–12 If necessary.Access 2007: VBA Programming A-6: Do it! Associating code with an event Here’s how Here’s why 1 Open the code window for frmRetailer 2 From the Object list.") This code displays a message box with this text. 5 Click (The Save Objects button is on the Standard toolbar. Tell students that they need to scroll up. select Activate You’ll attach code to the Activate event of this Form object. Switch to Access PR 6 Switch to Form view Click OK A message box appears showing the text you specified in the MsgBox function.) It appears on a new object tab. 8 Click the Retailer Form tab The message appears again. EV Press q Type the following code: ("You cannot edit data in this form. Tell students that they can also press Ctrl + S. This event is triggered whenever the form is made active. To close the message box. 7 Open frmOrder in Form view (Double-click it in the Navigation Pane. showing the complete syntax.) To update the database. not just when it’s opened. Click OK 9 Close both forms NOT FOR PRINTING OR INSTRUCTIONAL USE . IE The events for the Form object are listed in the Procedure list.

or Access. Hide. After setting a reference to an application’s object library. Object libraries provide the information about available objects in VBA to the Object Browser. such as App. NOT FOR PRINTING OR INSTRUCTIONAL USE . if you need to print the contents of a table in a specified format by using Word because printing in Access doesn’t provide formats. or Control. Each Microsoft Office application. you can use the builtin methods. PR To display the Object Browser. Object Browser in VBE. and Show to manage forms in VBA. you can select Microsoft Word 12. The relevant object library is copied to the hard disk when you install the application. has its own object library. Collection. Pressing F2 in the VBE can also open Object Browser. choose View. You can also display help information on any object by using the Object Browser window. properties. You can set a reference to an application’s object library by selecting the relevant object library from the References dialog box.Visual Basic Editor 1–13 Topic B: Object Browser You can view an object’s builtin properties and methods when creating procedures in a module. The builtin properties and methods of an object are the properties and methods that are provided by the object itself. A class is the basic pattern used when an object is created. You can also search for a specific method or an event of an object in the Object Browser. Classes. such as Word. or click the Object Browser button on the Visual Basic toolbar. define methods. Excel. and constants in the available object libraries. such as Load.0 Object Library from the References dialog box. methods. For example. and events for an object. For example. An object is created at run time from a class contained in the object libraries. Then. properties. The Object Browser window Object Browser is a window that displays the classes. You can use the Object Browser window to examine all objects that are available in VBA and in Access. You can use the Object Browser to view the properties and methods of an object. Object libraries W Explanation EV IE An object library is a file that contains all information about the object model of an application. you can use all Word objects in your code. References from VBE to open the References dialog box. events. You can choose Tools. you can use the objects of that application in your code.

procedures. and the name of the library to which it belongs. • Details pane. • Classes list. For example. events and methods of an object are defined in class. the Details pane displays the method name. arguments (if available). You can select an available object library from this list. This displays the classes available in the selected object library. and functions. This displays the methods and properties that belong to the object that is selected in the Classes list. A library file contains all information about various classes. This describes the selected project.1–14 Access 2007: VBA Programming Details pane Methods/Properties list IE Objects/Modules list W Project/Library list EV Exhibit 1-3: The Object Browser window The Object Browser window. methods. its syntax. as shown in Exhibit 1-3. NOT FOR PRINTING OR INSTRUCTIONAL USE . class. the Project/Library list contains <All libraries>. library. or properties. PR • Members Of <classname> list. By default. The properties. if you select a method from the Objects/Modules list. uses various object libraries and displays the following information: • Project/Library list. objects.

9 Observe the Details pane To view the details of the WindowHeight property. You’ll view the information about the Access library. select Form Scroll down the list. Maximize the window. 6 From the Objects/Modules list. if necessary.) To view the details of this property. 5 Observe the Objects/Modules list It shows all the objects and modules that are available in the Access library. select Access NOT FOR PRINTING OR INSTRUCTIONAL USE . Object Browser W 1 Open the code window for frmProduct (The first dropdown list. select WindowHeight (In the lower part of the list. 2 Choose View. IE 3 Observe the Project/Library list (To open the Object Browser window. 8 From the Methods/Properties list.Visual Basic Editor Do it! B-1: 1–15 Examining the Object Browser window Here’s how Here’s why Tell students that they can also press F2 to open the Object Browser window. 7 Observe the Methods/Properties list (Scroll through the list.) By default. All Libraries appear.) You’ll view the various objects and classes of the Access library and their methods and events by using Object Browser. PR EV 4 From the Project/Library list. A green brick indicates methods and a hand icon pointing to an index indicates properties.) It shows all the methods and properties that are available for the Form object.

NOT FOR PRINTING OR INSTRUCTIONAL USE . After the search is complete. as shown in Exhibit 1-4. and events of an object. 5 Observe the Classes list The classes in VBAWindow1 appear in bold. select All Libraries PR 2 In the Search Text box. properties. then click the Search button.) To start search.1–16 Access 2007: VBA Programming Object Browser’s search feature You use the search feature of the Object Browser to view the methods. enter Form_frmRetailer You’ll use the Object Browser to view the methods. enter the name of the project. and events of all objects in Form_frmRetailer. W Explanation Search Text box IE Search button EV Search Results section Exhibit 1-4: The Object Browser with the Search Results section Do it! B-2: Searching in the Object Browser Here’s how Here’s why 1 From the Project/Library list. properties. or object whose information you want to view. The Object Browser searches for the text you entered and displays the results in the Search Results section. the Search Results section is added to the Object Browser window. database. 3 Click (The Search button is in the Object Browser window. 4 Observe the Search Results section This displays the VBAWindow1 as library and Form_frmRetailer as class. To do so.

if available. PR Close the form NOT FOR PRINTING OR INSTRUCTIONAL USE . and arguments. its syntax. select This section displays the method name. This displays VBA as library.Visual Basic Editor Tell students to scroll down. 13 Observe the Members of ‘Conversion’ list The function Clnt displays in a dotted box. select VBA To start the search. and Clnt as member. events. 12 Observe the Classes list The class Conversion displays in a dotted box. EV 11 Observe the Search Results section 15 Switch to Access To return to the Database window. 14 Close the Object Browser Click the Close Window button on the upper right corner of the Code window. properties. Conversion as class. or constants that have code written for them appear bold. You’ll search for a function called ‘cInt’ provided by the VBA library. Form_Activate Observe the Details pane W 7 Under Members of ‘Form_frmRetailer’. 6 Observe the Members of the ‘Form_frmRetailer’ list 1–17 The methods. cInt 10 Click IE 8 From the Project/Library list. 9 Edit the Search Text box to read To provide the name of the function.

4 Is a form a collection object? Yes. by itself. The following syntax declares a collection: IE Dim CollectionName as new Collection To add an item to a collection. you can define your own properties and methods for the object. You can create your own collection object. and option buttons. This helps you refer to a group of related items as a single object. These controls are part of the Controls collection.1–18 Access 2007: VBA Programming Topic C: Collections A collection object contains multiple objects that are treated as a single item. which includes objects that you define. These objects might be of the same type or of different types. For example. is a collection object. you must declare a collection object to create it. the Forms collection and Controls collection are builtin collections. and Access has several. All forms that are open at any point are part of the Forms collection. For example. To remove all items in a collection. NOT FOR PRINTING OR INSTRUCTIONAL USE . such as labels. 2 What are builtin collections? PR Builtin collections are those provided by Access. each form. you may have a number of forms in your application. For example. In this case. C-1: Understanding collection objects Questions and answers 1 What’s a collection object? A collection object is a set of objects that can be treated as a single unit. use the Remove method. command buttons. Each form might contain several controls. To remove an item. you use the Add method. Builtin collections Do it! EV Builtin collections are those provided by the application itself. you can declare all controls in a form as a collection. text boxes. use the Remove method in a loop. A collection object has properties and methods of its own that define the objects contained in it. called custom collection. 3 What’s the Forms collection? It’s a collection of all forms that are open at any point of time in an application. W Explanation Because collection is an object type in VBA. Collections simplify the code if you need to perform the same operation on all objects in a collection.

An Access application consists of multiple form and report objects. You use the Control object type if you need to make a change to all controls of the same type.Visual Basic Editor 1–19 Controls collection A control on a form or a report is a control object. 7 Update the database Click the Save Objects button in the toolbar. 8 Close VBE Click the Close button. NOT FOR PRINTING OR INSTRUCTIONAL USE .) You’ll write code to clear the text boxes by using Controls collection. select Form The Form_Load event procedure appears in the Code window. IE Observe the form 2 Switch to Design view By default. press t and then type the following code: PR For Each Ctl In Form_frmLogin If TypeOf Ctl Is TextBox Then Ctl. then the focus is set on the text box.SetFocus Ctl. the Object list displays General and the Procedure list displays Declarations. and the text is set to blank. Each form consists of several controls that belong to the Controls collection of that form. If the control is TextBox. each report consists of several controls that belong to the Controls collection of that report. Do it! C-2: W Explanation Using the Controls collection Here’s how Here’s why 1 Open frmLogin in Form view (By default. In the same way. EV 3 Open the form’s Code window Dim Ctl as Control Press e 5 From the Object list. A control has methods and properties of its own. 6 In the Form_Load event procedure. 4 In the General Declarations section. type the following code: To declare Ctl as a variable of the Control generic object type.Text = "" End If Next The For Each…Next loop used in this code checks all controls in the form. user name and password are in their respective text boxes.

PR EV IE 11 Close the database W 10 Close the form NOT FOR PRINTING OR INSTRUCTIONAL USE .1–20 Access 2007: VBA Programming 9 Switch to Form view The form appears with a blank user name and password.

18 Close VBE. 14 Close the form. 3 Modify the Caption property of frmLogin form to read Login Form by using the Properties window. PR 13 Switch to Form view and ensure the validity of your code. 10 Open the Code window for frmEmployee. 12 Update the database. You learned that you can search methods. NOT FOR PRINTING OR INSTRUCTIONAL USE . 8 Open Practice Objects. you’ll write code to change a form’s properties. You also learned how to use the Controls collection. 9 Open and observe frmEmployee.) 17 Close Object Browser. Topic C In this topic.) 7 Update the database. and test whether or not you can close the database.Visual Basic Editor 1–21 Unit summary: Visual Basic Editor In this topic. Topic B In this topic. 19 Close the database. 11 Using control collections. select All Libraries. properties. and events of an object by using the Object Browser. 1 Open Practice objects. write a code to clear the text in all text boxes. you learned how to use the Object Browser. 2 Open the code window for frmLogin. You also learned how to associate code with an event by using an event procedure. 16 Use Object Browser to search for the methods used in frmEmployee. you learned about collection objects. You learned how to modify properties and use methods by using a Code window. W Topic A Independent practice activity IE In this activity. and enter Form_frmEmployee in the Search Text box. 6 Use a method to close the database. (Hint: From the Project/Library list. 15 Open the code window for frmEmployee. (Hint: Use the Quit acQuitSaveAll method in the Click event of the cmdQuit button of frmLogin. you learned about objects. EV 5 Update the database. 4 Switch to Form view and ensure that form caption is changed to Login Form. and clear the text from text boxes. switch to Access.

) The object's name. D A database that contains objects. For example. it can’t be treated as a single unit. NOT FOR PRINTING OR INSTRUCTIONAL USE . 4 What’s displayed in the Properties window? (Choose all that apply. True IE 2 True or false: An object’s method is a behavior or action that’s performed by the object and can be used to accomplish specific tasks. EV A C The object's behaviors. or click the Object Browser button on the Visual Basic toolbar. you can declare all controls in a form as a single collection in which the controls might be of the same type or of different types. reports. B The object's properties. and queries. B A set of programs that’s used to perform specific tasks. Pressing F2 in the VBE can also open Object Browser. 5 How do you display the Object Browser? To display the Object Browser. choose View.) W A Properties that can be set at either design time or run time. PR False. The collection object can be treated as a single unit. Object Browser in VBE. D The current value of the properties. forms. C A programming concept in which all the elements of a program are considered to be objects.1–22 Access 2007: VBA Programming Review questions 1 What’s Object Oriented Programming (OOP)? (Choose one. 6 True or false: Because a collection object consists of multiple objects that have been put together. such as tables. 3 What’s a procedure? A procedure is a block of VBA program code that performs a specific task. macros.