access2007vba programming instrutorsedition
TRANSCRIPT
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
1/40
A c c e s s 2 0 0 7 :
V B A P r o g r a m m i n g
Instructor’s Edition
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
2/40
Access 2007: VBA Programming
Series Product Managers: Charles G. Blum and Adam A. WilcoxWriter: Don Tremblay
Developmental Editor: Steve English
Copyeditor: Ken Maher
Keytester: Cliff Coryea
Series Designer: Adam A. Wilcox
COPYRIGHT © 2007 Axzo Press
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
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 andmay 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-6ISBN 13: 978-1-4239-5102-5
Printed in the United States of America
1 2 3 4 5 GLOB 06 05 04 03
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
3/40
C o n t e n t s
Introduction iii
Topic A: About the manual............................................................................... iv Topic B: Setting student expectations .............................................................. ix Topic C: Classroom setup.................................................................................xii Topic D: Support.............................................................................................. xvi
Visual Basic Editor 1-1 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 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 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
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
4/40
ii Access 2007: VBA Programming
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
5/40
iii
Introduction
After reading this introduction, you’ll know
how to:
A Use ILT Series training manuals in
general.
B Use prerequisites, a target student
description, course objectives, and a skillsinventory to set students’ expectations
properly for the course.
C Set up a classroom to teach this course.
D Get support for setting up and teaching this
course.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
6/40
iv Access 2007: VBA Programming
Topic A: About the manual
ILT Series philosophy
Our goal is to make you, the instructor, as successful as possible. To that end,
our training manuals facilitate students’ learning by providing structured interactionwith the software itself. While we provide text to help you explain difficult concepts,
the hands-on activities are the focus of our courses. Leading the students through these
activities will teach the skills and concepts effectively.
We believe strongly in the instructor-led classroom. For many students, having a
thinking, feeling instructor in front of them is always the most comfortable way to learn.
Because the students’ focus should be on you, our manuals are designed and written to
facilitate your interaction with the students and not to call attention to manuals
themselves.
We believe in the basic approach of setting expectations, then teaching, and providing
summary and review afterwards. For this reason, lessons begin with objectives and end
with summaries. We also provide overall course objectives and a course summary to provide both an introduction to and closure on the entire course.
Our goal is your success. We encourage your feedback in helping us to improve our
manuals continually to meet your needs.
Manual components
This manual contains these major components:
• Table of contents
• Introduction
• Units
• Appendix
• Course summary
• Quick reference
• Glossary
• Index
Each element is described below.
Table of contents
The table of contents acts as a learning roadmap for you and the students.
Introduction
The introduction contains information about our training philosophy and our manual
components, features, and conventions. It contains target student, prerequisite,
objective, and setup information for the specific course. Finally, the introduction
contains support information.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
7/40
Introduction v
Units
Units are the largest structural component of the actual course content. A unit begins
with a title page that lists objectives for each major subdivision, or topic, within the unit
Within each topic, conceptual and explanatory information alternates with hands-on
activities. Units conclude with a summary comprising one paragraph for each topic, and
an independent practice activity that gives students an opportunity to practice the skills
they’ve learned.The conceptual information takes the form of text paragraphs, exhibits, lists, and tables.
The activities are structured in two columns, one telling students what to do, the other
providing explanations, descriptions, and graphics. Throughout a unit, instructor notes
are found in the left margin.
Appendices
An appendix is similar to a unit in that it contains objectives and conceptual
explanations. However, an appendix doesn’t include hands-on activities, a summary, or
an independent practice activity.
Course summary
This section provides a text summary of the entire course. It’s useful for providing
closure at the end of the course. The course summary also indicates the next course in
this series, if there is one, and lists additional resources students might find useful as
they continue to learn about the software.
Quick reference
The quick reference is an at-a-glance job aid summarizing some of the more common
features of the software.
Glossary
The glossary provides definitions for all of the key terms used in this course.
Index
The index at the end of this manual makes it easy for you and your students to find
information about a particular software component, feature, or concept.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
8/40
vi Access 2007: VBA Programming
Manual conventions
We’ve tried to keep the number of elements and the types of formatting to a minimum
in the manuals. We think this aids in clarity and makes the manuals more elegantlooking. But there are some conventions and icons you should know about.
Instructor note/icon Convention Description
Italic text In conceptual text, indicates a new term or feature.
Bold text In unit summaries, indicates a key term or concept. In anindependent practice activity, indicates an explicit item
that you select, choose, or type.
Code font Indicates code or syntax.
Longer strings of ► code will look ►
like this.
In the hands-on activities, any code that’s too long to fit
on a single line is divided into segments by one or more
continuation characters (►). This code should be enteredas a continuous string of text.
Instructor notes. In the left margin, provide tips, hints, and warnings forthe instructor.
Select bold item In the left column of hands-on activities, bold sans-seriftext indicates an explicit item that you select, choose, or
type.
Keycaps likee Indicate a key on the keyboard you must press.
Warning icon.Warnings prepare instructors for potential classroom
management problems.
Tip icon.Tips give extra information the instructor can share with
students.
Setup icon.Setup notes provide a realistic business context for
instructors to share with students, or indicate additional
setup steps required for the current activity.
Projector icon.Projector notes indicate that there is a PowerPoint slide
for the adjacent content.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
9/40
Introduction vii
Hands-on activities
The hands-on activities are the most important parts of our manuals. They’re divided
into two primary columns. The “Here’s how” column gives short directions to thestudents. The “Here’s why” column provides explanations, graphics, and clarifications.
To the left, instructor notes provide tips, warnings, setups, and other information for the
instructor only. Here’s a sample:
Do it! A-1: Creating a commission formula
Here’s how Here’s why
1 Open Sales This is an oversimplified sales compensationworksheet. It shows sales totals, commissions,and incentives for five sales reps.
Take the time to makesure your studentsunderstand thisworksheet. We’ll be here awhile.
2 Observe the contents of cell F4
The commission rate formulas use the name“C_Rate” instead of a value for the commission
rate.
For these activities, we’ve provided a collection of data files designed to help students
learn each skill in a real-world business context. As students work through the activities
they modify and update these files. Of course, they might make a mistake and,
therefore, want to re-key the activity starting from scratch. To make it easy to start over,
students rename each data file at the end of the first activity in which the file is
modified. Our convention for renaming files is to add the word “My” to the beginning
of the file name. In the above activity, for example, students are using a file called
“Sales” for the first time. At the end of this activity, they save the file as “My sales,”
thus leaving the “Sales” file unchanged. If students make mistakes, they can start over
using the original “Sales” file.In some activities, however, it may not be practical to rename the data file. Such
exceptions are indicated with an instructor note. If students want to retry one of these
activities, you need to provide a fresh copy of the original data file.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
10/40
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
11/40
Introduction ix
Topic B: Setting student expectations
Properly setting students’ expectations is essential to your success. 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
Students taking this course should be familiar with personal computers and the use of a
keyboard and a mouse. Furthermore, 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
The target student for this course should be familiar with Access 2007 and Visual Basicfor Applications. Students should be able to use various VBA programming elements.
Students get the most out of this course, if their goal is to become proficient in working
with objects and collections, and implementing ActiveX Data Objects.
Course objectives
You should share these overall course objectives with your students at the beginning of
the day. This approach gives the students an idea about what to expect and also helps
you identify students who might be misplaced. Students are considered misplaced whenthey lack the prerequisite knowledge or when they already know most of the subject
matter to be covered.
After completing this course, students will know how to:
• Work with objects, use Object Browser, identify collection objects, and use theControls collection.
• Manipulate data by declaring variables, combine data by using expressions, get
user input, create Sub and Function procedures, and call one procedure from
another.
• Use decision structures and use loop structures.
•
Identify ActiveX Data Objects (ADO) architecture and collections, connect to adatabase, work with a Recordset, and create a parameter query.
• Identify compile-time, run-time, and logical errors; use the debugging tools; and
write error-handling code.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
12/40
x Access 2007: VBA Programming
Skills inventory
Use the following form to gauge students’ skill level entering the class (students have
copies in the introductions of their student manuals). For each skill listed, have studentsrate their familiarity from 1 to 5, with 5 being the most familiar. Emphasize that this
isn’t a test. Rather, it’s intended to provide students with an idea of where they’re
starting from at the beginning of class. If a student is wholly unfamiliar with all the
skills, he or she might not be ready for the class. A student who seems to understand allof the skills, on the other hand, might need to move on to the next course in the series.
Skill 1 2 3 4 5
Work with objects, their properties, methods, and events
Use the Object Browser
Identify collection objects
Use the Controls collection
Examine data types and variables
Use operators and interaction functions
Observe modules and procedures
Examine procedure-, module-, and public-level scopes
Create and call a Sub procedure
Create and call a Function procedure
Use If…Then, If…Then…Else, and If…Then…ElseIf statements
Use the Select Case statement
Use the For…Next, For Each…Next, and Do While…Loop loops
Discuss ADO and ADO collections
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
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
13/40
Introduction xi
Skill 1 2 3 4 5
Discuss types of errors
Discuss debugging tools
Set a breakpoint
Add and delete a watch expression
Use Step Into
Work with the Immediate window
Use the Locals window
Write error-handling code
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
14/40
xii Access 2007: VBA Programming
Topic C: Classroom setup
All our courses assume that each student has a personal computer to use during the
class. Our hands-on approach to learning requires that they do. This topic gives
information on how to set up the classroom to teach this course. It includes minimumrequirements for the students’ personal computers, 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.
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. The
setup process described here may vary slightly from what you encounter. This also
applies to activities and screen shots throughout the course.
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
• CD-ROM drive
• SVGA at 1024 × 768, or higher resolution monitor
Software requirements
You need the following software:
•
Windows XP, Windows Vista, or Windows Server 2003• Microsoft Office 2007
Network requirements
The following network components and connectivity are also required for this course:
• Internet access, for the following purposes:
– Updating the Windows operating system and Microsoft Office 2007 at
update.microsoft.com
– Downloading the Student Data files (if necessary)
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
15/40
Introduction xiii
First-time setup instructions
1 Install Windows XP on an NTFS partition according to the software
manufacturer’s instructions.
Note: You can also use Windows Vista or Windows Server 2003, but the screen
shots in this course were taken using Windows XP, so students’ screens will
look somewhat different.
2 If the operating system is Windows XP, then launch the Control Panel, open theDisplay Properties dialog box and apply the following settings:
• Theme — Windows XP
• Screen resolution — 1024 by 768 pixels
• Color quality — High (24 bit) or higher
3 If Windows was already loaded on this PC, verify that Internet Explorer is the
default Web browser. (If you installed Windows yourself, skip this step.)
a Click Start, All Programs, Internet Explorer.
b Choose Tools, Internet Options.
c Check “Internet Explorer should check to see whether it is the default
browser.”d Click OK to close the Internet Options dialog box.
e Close and re-open Internet Explorer.
f If a prompt appears, asking you to make Internet Explorer your default
browser, click Yes.
g Close Internet Explorer.
4 Create an Internet account for the student. Web access is required, an e-mail
account isn’t.
5 Open Internet Explorer and navigate to update.microsoft.com. Update the
operating system with the latest critical updates and service packs.
6 Install Microsoft Office 2007 according to the software manufacturer’sinstructions, as follows:
a When prompted for the CD key, enter the code included with your
software.
b Select the Customize installation option and click Next.
c Activate the Installation Options tab.
d For Access 2007, Office Shared Features, and Office Tools, click the
dropdown arrow and choose Run all from My Computer.
e Set all but the following to Not Available: Access 2007, Office Shared
Features, and Office Tools.
f Click Install Now.
g On the last screen of the Office 2007 installer, click Go to Office Online.Internet Explorer displays the Office Online Web site, and the installer
window closes.
h On the Office Online Web page, activate the Downloads tab.
i Download and install any available updates.
j Close Internet Explorer.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
16/40
xiv Access 2007: VBA Programming
7 If you don’t have the data CD that came with this manual, download the Student
Data files for the course. You can download the data directly to studentmachines, to a central location on your own network, or to a disk.
a Connect to www.courseilt.com/instructor_tools.html.
b Click the link for Microsoft Access 2007 to display a page of course
listings, and then click the link for Access 2007: VBA Programming.
c Click the link for downloading the Student Data files, and follow theinstructions that appear on your screen.
8 Create a student data folder on each student’s computer, and copy the Student
Data files to that folder.
9 Start Access 2007.
a Activate the software. After activating, the Welcome to the 2007 Microsoft
Office System dialog box appears.
b On the Privacy Options screen, verify that “Search Microsoft Office Online
for Help content when I’m connected to the Internet” is checked.
c Verify that “Download a file periodically that helps determine system
problems” is cleared.
d Verify that “Sign up for the Customer Experience Improvement Program”is cleared.
e Click Next.
f Select “I don’t want to use Microsoft Update.”
g Click Finish to close the dialog box.
10 To prevent students from receiving a security warning when they open files in
Access 2007, 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.
b On the Trust Center page, click Trust Center Settings. The Trust Center
dialog box opens.c Navigate to the Trusted Locations page.
d Click Add new location. The Microsoft Office 2007 Trusted Location
dialog box opens.
e Click Browse and navigate to the student data folder.
f Click OK to close the Browse dialog box.
g Check Subfolders of this location are also trusted.
h Click OK to close the Microsoft Office 2007 Trusted Location dialog box.
i Click OK to close the Trust Center dialog box.
11 Make the student data folder the default file location.
a In the left panel of the Access Options dialog box, choose Popular. b Under Creating databases, click Browse, and navigate to the student data
folder.
c Click OK to close the Default Database Path dialog box.
d Click OK to close the Access Options dialog box.
e Close Access 2007.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
17/40
Introduction xv
Setup instructions for every class
Every time you teach this course, you need to perform the following steps to set up each
student computer.
1 Delete the contents of the Student Data folder, if necessary. (If this is the first
time you’re teaching the course, create a folder named Student Data at the root
of the hard drive.)
2 Copy the data files to the Student Data folder. (See the download instructions in
the preceding section.)
3 Open Internet Explorer and navigate to update.microsoft.com. Update the
operating system and Office 2007.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
18/40
xvi Access 2007: VBA Programming
Topic D: Support
Your success is our primary concern. If you need help setting up this class or teaching a
particular unit, topic, or activity, please don’t hesitate to get in touch with us.
Contacting us
Please contact us through our Web site, www.axzopress.com. You will need to provide
the name of the course, and be as specific as possible about the kind of help you need.
Instructor’s tools
Our Web site provides several instructor’s tools for each course, including course
outlines and answers to frequently asked questions. To download these files, go to
www.axzopress.com. Then, under Downloads, click Instructor-Led Training and
browse our subject categories.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
19/40
1–1
U n i t 1
Visual Basic Editor
Unit time: 65 minutes
Complete this unit, and you’ll know how to:
A Work with objects, their properties,
methods, and events.
B Use Object Browser to get information
about objects.
C Identify collection objects and use the
Controls collection.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
20/40
1 – 2 Access 2007: VBA Programming
Topic A: Objects
Explanation Visual Basic for Applications, or VBA, is a programming language that comes as a partof the Microsoft Office suite and is shared among Office applications.
You can decide to gofurther into OOP astime allows.
VBA is based on Object Oriented Programming (OOP). In OOP , all the elements of a
program are considered objects. Objects constitute a way of organizing and relatingvariables, data, and procedures. Objects can be visible things, such as forms, command
buttons, and text boxes, or more conceptual elements, such as reports, queries, or even
entire applications. The details of OOP are outside the scope of this unit, but a basic
understanding is sufficient to start programming.
An object has certain characteristics and behavior. These characteristics are the object’s
properties and can be set at either design time or run time of a project. Design time is
when you design forms, place controls in the form, set properties, and write code for the
project. Run time is when the project is executing. You can write VBA code to
manipulate forms, reports, command buttons, and other controls. Visual Basic Editor
(VBE) is the environment in which you write, edit, and test VBA code. The VBE helps
you manipulate object properties and methods. For example, you can change text in a
text box and also hide the text box by writing code in VBE. You can access VBEthrough any Microsoft Office application.
Each Office application has its own set of objects or object model. For example, Word
contains document and paragraph objects, and Access contains table and form objects.
An object’s method is a behavior or action that’s performed by the object and can be
used to accomplish specific tasks. For example, Rename is a method that changes the
name of an object. An application consists of two types of objects, individual objects
and collection objects. A collection object is an arranged group of items that can be
treated as a unit. For example, the Forms collection includes all currently open form
objects.
An object can respond to events. For instance, some events occur when a form opens, a
button is clicked, or a text box loses focus. You can write code that runs when an eventoccurs.
Access objects
Tables, queries, and forms in an Access application are themselves individual. In Accessand other Office applications, one object can contain other objects. For instance, a form
object contains controls, such as buttons and check boxes, and a table object contains
objects, such as fields and indexes. In VBA, the applications themselves are also
objects.
Generic object types
You can use Generic object types when you aren’t sure what type of object you want to
work with. Both Access and VBA provide generic object types. For example, Object is
a generic object type that VBA provides and Access provides Control as its generic
object type. You can assign any type of object or control to this generic object type.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
21/40
Visual Basic Editor 1 –3
Do it! A-1: Discussing objects
Questions and answers
1 What’s an object?
An object is an entity that has specific characteristics and behavior. In Access, tables,
forms, and controls are objects.
2 Is VBA shared among Office applications? If so, why?
Yes, VBA is shared by all Office applications because it’s part of the Microsoft Office suite.
3 Is Access an object in VBA? If so, why?
Yes, Access is an object, because applications are also objects in VBA and can be programmed or manipulated.
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 touse.
5 What generic object types are available in VBA and Access?
VBA provides the Object type and Access provides the Control type.
If time allows, havestudents think of othersimple objects to modeland list the relevant properties, methods, andevents.
6 Consider modeling a real-world object – a toaster. What are its properties,
methods, and events?
Answers will vary. Properties: plugged in (a true/false property), color, size, number of slots,toasting time. Methods: toast bread, change toasting time, pop toast up. Events: lever
pushed down, toasting time dial changed, lever manually popped up.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
22/40
1 – 4 Access 2007: VBA Programming
Object properties
Explanation You can modify properties and methods. You can also attach code to the events of anobject to change its appearance, behavior, and the action it performs. You can also use
VBA objects to create procedures that perform more complex tasks than simply
executing a set of recorded actions. A procedure is a block of VBA program code that
performs a specific task.
The Properties window
The Properties window displays the name of the object, its properties, and the current
value of the properties, as shown in Exhibit 1-1. The two tabs in this window are
Alphabetic and Categorized tabs. The Alphabetic tab displays the properties of the
selected object alphabetically, whereas the Categorized tab displays the properties for
the selected object by category, such as Data, Event, Format, and Other. For example,
properties, such as Caption, BorderStyle, and AutoCenter are in the Format category.
Object box
Property names Property values
Exhibit 1-1: The Properties window
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
23/40
Visual Basic Editor 1 –5
Do it! A-2: Examining the Properties window
Here’s how Here’s why
1 Start Access Choose Start, All Programs, Microsoft Office,Microsoft Office Access 2007.
2 Open Objects From the current unit folder.Help students navigate tothe current unit folder.
3 In the Navigation Pane, display
Forms
If necessary.
4 Open frmOrder in Design view (Right-click it and choose Design View.) You’llexamine the properties of this form.
5 On the Design tab, click (The View Code button is in the Tools group.)To open the Visual Basic Editor window. Thecode windows for other forms are also
displayed.
6 In the Object box list in theProperties pane, select frmOrder
(If necessary.) To select the properties for thefrmOrder form.
In the Properties window, observe
the Name property
(You can resize the pane to be able to see all the
property names.) It’s at the top of the list. This is
the name assigned to the form object.
Tell students to scrolldown.
7 In the Properties window, observe
the Caption property of the form
This is the name that appears on the object tabwhen the form is opened in Access.
Tell students to scroll toview the tasks.
8 In the Properties window, activate
the Categorized tab
To view the properties grouped according to thetasks they perform.
9 Observe the Properties window The properties are categorized based on thetasks, such as Data, Event, Format, and Other.
10 In the Properties window, activate
the Alphabetic tab
To view the properties in alphabetical order.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
24/40
1 – 6 Access 2007: VBA Programming
Changing properties
Explanation You can change option properties, such as changing the caption of a form to reflect thedata it contains.
You change a property of an Access object by selecting the object and then editing the
property value in the Properties window. The object immediately reflects the change.
Some properties have a list of predefined values from which you can select. This listappears in the value column of the Properties window. For example, you can select a
value for the BorderStyle property of a form, such as 0-None or 2-sizable.
Do it! A-3: Modifying the object properties
Here’s how Here’s why
Tell students that theymight need to scroll up.
1 In the Properties window, observe
the Caption property
The caption frmOrder appears as the property
value.
2 Click (The View Microsoft Office Access button is onthe Standard toolbar of the VBE window.) To
switch to the Microsoft Access window.
Switch to Form view (The Form view button is on the status bar at thelower right of the Access window.) The caption
for the object tab is frmOrder.
3 Switch to Design view To return to the Design view of the form.
Students can alsoswitch by clicking therelevant buttons on thetask bar.
Tell students they canalso right-click the form’stab and choose Formview.
4 Switch back to the VBE window Click View Code.
5 In the Properties window, double-
click Caption
You’ll change the caption of the form.
6 Edit the Property value to read
Order Form
To change the caption to Order Form.
Presse
7 Switch to AccessStudents can click the Access button in the VBEor on the taskbar.
8 Switch to Form view The caption of the form reads Order Form.
9 Update and close the form
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
25/40
Visual Basic Editor 1 –7
Using the Code window
Explanation You can control object properties by writing VBA code in the Code window. Eachobject that appears in the Project Explorer window has a separate Code window
associated with it, such as the one shown in Exhibit 1-2. To open the Code window,
double-click a form or module in the Project Explorer window. A module includes
statements, declarations, and procedures that are stored as a single unit and contains one
or more related procedures. The two types of modules in Access are Standard modulesand Class modules. Class modules contain the definition for a new object. The
procedures defined in a Class module become the properties and method for the object.
Standard modules contain procedures that are available to other procedures throughout
your project. You can add a new module in a project by choosing Insert, Module. The
Code window that includes the code for a specific form or its control is also a Standard
module by itself. It’s known as Form module.
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 . 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 . When you select an event from the Procedure list, the procedure
associated with that event appears in the Code window. If you select an object from the
Object list, the definition of the object’s default procedure appears in the Code window.
In such cases, you don’t need to select the event from the Procedure list. For example,
when you select Form from the Object list, the Load event procedure for the form
appears in the Code window by default.
Procedure listObject list
Exhibit 1-2: A sample Code window
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
26/40
1 – 8 Access 2007: VBA Programming
Following is the general syntax for setting object properties through code:
object.property = value
In this syntax, object represents the name of the object, property is the property
name, and value is the value you want to assign to the property. The object name and
the property name are separated by a period (.). There are no spaces before or after the
period.
For example, to change the caption of the form named frmRetailer, you would enter the
code:
Form_frmRetailer.Caption ="Retailer Form"
In this example, the Caption property of the form frmRetailer is set to Retailer Form.
When you type a period after an object name, the Auto List option of VBA displays a
list of object members, such as data type or property from which you can choose. This
helps you to avoid incorrectly typing a name that isn’t a method or property of the
specified object.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
27/40
Visual Basic Editor 1 –9
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 usingcode.
2 Switch to VBE In the Design tab, click View Code.
Tell students to resize theCode window ifnecessary.
3 In the Objects - Form_frmRetailer
window, click as shown
To display the Object list, which includes the
objects associated with the form.
4 From the Object list, select Form
(You’ll write code to change the caption of theform.) These lines of code appear automatically.
In the first line, Form_Load() is the name of the
event procedure. The Load event of a form
occurs when the form is opened and its controls
display.
5 Presst To indent the code for better readability.
6 Type the following code:
Form_frmRetailer.c
An Auto List appears as soon as you type the
period, then when you press C the selection
moves to items starting with that letter.
Presst The word Caption appears automatically in thecode line.
Type the following code:
="Retailer Form"
To change the form caption to Retailer Form.
7 Switch to Access and to Form
view
The caption of the form reads Retailer Form.
Update the database Click Save on the Quick Access toolbar.
8 Close the form
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
28/40
1 – 10 Access 2007: VBA Programming
Using methods
Explanation The actions of an object are defined by the methods attached to it. For example, Quit isa method of the Application object. You can use this method to quit Microsoft Access.
The Quit method has a parameter, 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, with or without saving according to your answer.You can also close the dialog box by clicking the Cancel button.
• acQuitSaveAll: Saves all objects and then quits Microsoft Access.
• acQuitSaveNone: Quits Microsoft Access without saving the changes
Do it! A-5: Using a method
Here’s how Here’s why
1 Open the code window for
frmOrder
Open the form in Design view, then switch to itscode window.
2 From the Object list, selectcmdClose
You’ll apply the Quit method to the Close button.
3 Presst
Type the following code:
Application.
An Auto List appears, providing object classesand data types from which you can choose.
Type the following code:
Quit acQuitPrompt
You can also press Tab after you type ac.
4 Close the Code window Click the Close Window button on the upperright corner of the Code window.
5 Switch to Form view Switch to Access then to Form view.
6 Edit the Quantity box to read 200 To provide a new quantity.
7 Close the formA message box appears, prompting you to save
changes.
Tell students that, if theytried to close Access,they’d have received thesame prompt.
8 Click Yes To save the change and close the form.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
29/40
Visual Basic Editor 1 –11
Attaching code to events
Explanation A procedure can run in response to a specific user action, such as clicking a button. Youdo this by associating the code to an object event. Events include user actions, such as
mouse clicks, double-clicks, and opening or closing of forms.
When you associate code with an event, the code executes when the event occurs, such
as when another action triggers the event. You use event procedures to associate code
with an event. The events for the object selected in the Object list are listed in the
Procedure list. For example, 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. The Activate event of a form occurs when the form becomes the active window.
To program an event, double-click the object to display the Code window. Then, select
the object, select an event from the Procedure list, and enter the code you want.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
30/40
1 – 12 Access 2007: VBA Programming
Do it! A-6: Associating code with an event
Here’s how Here’s why
1 Open the code window for
frmRetailer
2 From the Object list, select Form If necessary.
3 Click as shown
The events for the Form object are listed in the
Procedure list.
Tell students that theyneed to scroll up.
From the Procedure list, select
Activate
You’ll attach code to the Activate event of this
Form object.
4 Presst and type thefollowing code:
MsgBox
Pressq The Auto Quick Info feature appears, showingthe complete syntax.
Type the following code:
("You cannot edit data in this form.")
This code displays a message box with this text.
Tell students that they canalso press Ctrl + S.
5 Click (The Save Objects button is on the Standardtoolbar.) To update the database.
Switch to Access
6 Switch to Form view A message box appears showing the text youspecified in the MsgBox function.
Click OK To close the message box.
7 Open frmOrder in Form view (Double-click it in the Navigation Pane.) Itappears on a new object tab.
8 Click the Retailer Form tab The message appears again. This event istriggered whenever the form is made active, not
just when it’s opened.
Click OK
9 Close both forms
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
31/40
Visual Basic Editor 1 –13
Topic B: Object Browser
Explanation You can view an object’s builtin properties and methods when creating procedures in amodule. The builtin properties and methods of an object are the properties and methods
that are provided by the object itself. For example, you can use the builtin methods,
such as Load, Hide, and Show to manage forms in VBA. You can use the Object
Browser to view the properties and methods of an object. You can also search for a
specific method or an event of an object in the Object Browser. Object libraries provide
the information about available objects in VBA to the Object Browser.
Object libraries
An object library is a file that contains all information about the object model of an
application. Each Microsoft Office application, such as Word, Excel, or Access, has its
own object library. The relevant object library is copied to the hard disk when you
install the application. You can set a reference to an application’s object library by
selecting the relevant object library from the References dialog box. You can choose
Tools, References from VBE to open the References dialog box. After setting a
reference to an application’s object library, you can use the objects of that application inyour code. For example, 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, you can select
Microsoft Word 12.0 Object Library from the References dialog box. Then, you can use
all Word objects in your code.
The Object Browser window
Object Browser is a window that displays the classes, properties, methods, events, and
constants in the available object libraries. A class is the basic pattern used when an
object is created. Classes, such as App, Collection, or Control, define methods,
properties, and events for an object. An object is created at run time from a class
contained in the object libraries. You can use the Object Browser window to examineall objects that are available in VBA and in Access. You can also display help
information on any object by using the Object Browser window.
To display the Object Browser, choose View, Object Browser in VBE, or click the
Object Browser button on the Visual Basic toolbar. Pressing F2 in the VBE can also
open Object Browser.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
32/40
1 – 14 Access 2007: VBA Programming
Project/Library
list
Methods/Properties
listObjects/Modules
list
Details pane
Exhibit 1-3: The Object Browser window
The Object Browser window, as shown in Exhibit 1-3, uses various object libraries and
displays the following information:
• Project/Library list. You can select an available object library from this list. A
library file contains all information about various classes, objects, procedures,
and functions. By default, the Project/Library list contains .
• Classes list. This displays the classes available in the selected object library. The
properties, events and methods of an object are defined in class.
• Members Of list. This displays the methods and properties that
belong to the object that is selected in the Classes list.
• Details pane. This describes the selected project, library, class, methods, or
properties. For example, if you select a method from the Objects/Modules list,
the Details pane displays the method name, its syntax, arguments (if available),
and the name of the library to which it belongs.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
33/40
Visual Basic Editor 1 –15
Do it! B-1: Examining the Object Browser window
Here’s how Here’s why
1 Open the code window for
frmProduct
Tell students thatthey can also press F2 toopen the Object Browserwindow.
2 Choose View,Object Browser
(To open the Object Browser window.Maximize the window, if necessary.) You’ll
view the various objects and classes of the
Access library and their methods and events byusing Object Browser.
3 Observe the Project/Library list (The first dropdown list.) By default, AllLibraries appear.
4 From the Project/Library list,
select Access
You’ll view the information about the Access
library.
5 Observe the Objects/Modules list It shows all the objects and modules that are
available in the Access library.
6 From the Objects/Modules list,
select Form
Scroll down the list.
7 Observe the Methods/Properties
list
(Scroll through the list.) It shows all the methods
and properties that are available for the Formobject. A green brick indicates methods and a
hand icon pointing to an index indicates
properties.
8 From the Methods/Properties list,
select WindowHeight
(In the lower part of the list.) To view the details
of this property.
9 Observe the Details pane To view the details of the WindowHeight property.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
34/40
1 – 16 Access 2007: VBA Programming
Object Browser’s search feature
Explanation You use the search feature of the Object Browser to view the methods, properties, andevents of an object. To do so, enter the name of the project, database, or object whose
information you want to view, then click the Search button. The Object Browser
searches for the text you entered and displays the results in the Search Results section,
as shown in Exhibit 1-4.
Search
Text boxSearch button
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,
select All Libraries
2 In the Search Text box, enter
Form_frmRetailer
You’ll use the Object Browser to view themethods, properties, and events of all objects in
Form_frmRetailer.
3 Click (The Search button is in the Object Browserwindow.) To start search. After the search is
complete, the Search Results section is added tothe Object Browser window.
4 Observe the Search Results
section
This displays the VBAWindow1 as library and
Form_frmRetailer as class.
5 Observe the Classes list The classes in VBAWindow1 appear in bold.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
35/40
Visual Basic Editor 1 –17
Tell students to scrolldown.
6 Observe the Members of the
‘Form_frmRetailer’ list
The methods, properties, events, or constants
that have code written for them appear bold.
7 Under Members of
‘Form_frmRetailer’, select
Form_Activate
Observe the Details pane
This section displays the method name, its
syntax, and arguments, if available.
8 From the Project/Library list,
select VBA
You’ll search for a function called ‘cInt’
provided by the VBA library.
9 Edit the Search Text box to read
cInt
To provide the name of the function.
10 Click To start the search.
11 Observe the Search Results
section
This displays VBA as library, Conversion as
class, and Clnt as member.
12 Observe the Classes list The class Conversion displays in a dotted box.
13 Observe the Members of
‘Conversion’ list
The function Clnt displays in a dotted box.
14 Close the Object Browser Click the Close Window button on the upperright corner of the Code window.
15 Switch to Access
Close the form To return to the Database window.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
36/40
1 – 18 Access 2007: VBA Programming
Topic C: Collections
Explanation A collection object contains multiple objects that are treated as a single item. This helpsyou refer to a group of related items as a single object. For example, you can declare all
controls in a form as a collection. A collection object has properties and methods of its
own that define the objects contained in it. You can create your own collection object,
called custom collection, which includes objects that you define. In this case, you can
define your own properties and methods for the object. Collections simplify the code if
you need to perform the same operation on all objects in a collection.
Because collection is an object type in VBA, you must declare a collection object to
create it. The following syntax declares a collection:
Dim CollectionName as new Collection
To add an item to a collection, you use the Add method. To remove an item, use the
Remove method. To remove all items in a collection, use the Remove method in a loop.
Builtin collectionsBuiltin collections are those provided by the application itself, and Access has several.
For example, you may have a number of forms in your application. All forms that are
open at any point are part of the Forms collection. Each form might contain several
controls, such as labels, text boxes, command buttons, and option buttons. These
controls are part of the Controls collection.
Do it! 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. These objectsmight be of the same type or of different types.
2 What are builtin collections?
Builtin collections are those provided by Access. For example, the Forms collection andControls collection are builtin collections.
3 What’s the Forms collection?
It’s a collection of all forms that are open at any point of time in an application.
4 Is a form a collection object?
Yes, each form, by itself, is a collection object.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
37/40
Visual Basic Editor 1 –19
Controls collection
Explanation A control on a form or a report is a control object. A control has methods and propertiesof its own. An Access application consists of multiple form and report objects. Each
form consists of several controls that belong to the Controls collection of that form. In
the same way, each report consists of several controls that belong to the Controls
collection of that report. You use the Control object type if you need to make a change
to all controls of the same type.
Do it! C-2: Using the Controls collection
Here’s how Here’s why
1 Open frmLogin in Form view
Observe the form (By default, user name and password are in theirrespective text boxes.) You’ll write code to clear
the text boxes by using Controls collection.
2 Switch to Design view
3 Open the form’s Code window By default, the Object list displays General andthe Procedure list displays Declarations.
4 In the General Declarationssection, type the following code:
Dim Ctl as Control
To declare Ctl as a variable of the Control
generic object type.
Presse
5 From the Object list, select Form The Form_Load event procedure appears in the
Code window.
6 In the Form_Load event
procedure, presst and thentype the following code:
For Each Ctl In Form_frmLoginIf TypeOf Ctl Is TextBox Then
Ctl.SetFocusCtl.Text = ""
End If
Next
The For Each…Next loop used in this codechecks all controls in the form. If the control is
TextBox, then the focus is set on the text box,and the text is set to blank.
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
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
38/40
1 – 20 Access 2007: VBA Programming
9 Switch to Form view The form appears with a blank user name and password.
10 Close the form
11 Close the database
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
39/40
Visual Basic Editor 1 –21
Unit summary: Visual Basic Editor
Topic A In this topic, you learned about objects. You learned how to modify properties and usemethods by using a Code window. You also learned how to associate code with an
event by using an event procedure.
Topic B In this topic, you learned how to use the Object Browser. You learned that you cansearch methods, properties, and events of an object by using the Object Browser.
Topic C In this topic, you learned about collection objects. You also learned how to use theControls collection.
Independent practice activity
In this activity, you’ll write code to change a form’s properties, and clear the text from
text boxes.
1 Open Practice objects.
2 Open the code window for frmLogin.
3 Modify the Caption property of frmLogin form to read Login Form by using the
Properties window.
4 Switch to Form view and ensure that form caption is changed to Login Form.
5 Update the database.
6 Use a method to close the database. (Hint: Use the Quit acQuitSaveAll method in
the Click event of the cmdQuit button of frmLogin.)
7 Update the database, switch to Access, and test whether or not you can close the
database.
8 Open Practice Objects.
9 Open and observe frmEmployee.
10 Open the Code window for frmEmployee.
11 Using control collections, write a code to clear the text in all text boxes.
12 Update the database.
13 Switch to Form view and ensure the validity of your code.
14 Close the form.
15 Open the code window for frmEmployee.
16 Use Object Browser to search for the methods used in frmEmployee. (Hint: From
the Project/Library list, select All Libraries, and enter Form _ frmEmployee in theSearch Text box.)
17 Close Object Browser.
18 Close VBE.
19 Close the database.
NOT FOR PRINTING OR INSTRUCTIONAL USE
-
8/17/2019 Access2007VBA Programming InstrutorsEdition
40/40
1 – 22 Access 2007: VBA Programming
Review questions
1 What’s Object Oriented Programming (OOP)? (Choose one.)
A Properties that can be set at either design time or run time.
B A set of programs that’s used to perform specific tasks.
C A programming concept in which all the elements of a program are considered to be objects.
D A database that contains objects, such as tables, forms, reports, macros, and
queries.
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.
True
3 What’s a procedure?
A procedure is a block of VBA program code that performs a specific task.
4 What’s displayed in the Properties window? (Choose all that apply.)
A The object's name.
B The object's properties.
C The object's behaviors.
D The current value of the properties.
5 How do you display the Object Browser?
To display the Object Browser, choose View, Object Browser in VBE, or click the Object Browserbutton on the Visual Basic toolbar. Pressing F2 in the VBE can also open Object Browser.
6 True or false: Because a collection object consists of multiple objects that have been
put together, it can’t be treated as a single unit.
False. The collection object can be treated as a single unit. For example, you can declare allcontrols in a form as a single collection in which the controls might be of the same type or ofdifferent types.