Wrox Access 2003 VBA Programmers Reference Apr 2004 ISBN 0764559036 pdf
Access 2003 VBA Programmer’s Reference
Access 2003 VBA Programmer’s Reference
Patricia Cardoza Teresa Hennig Graham Seach
Armen Stein
Wiley Publishing, Inc.
Access 2003 VBA Programmer’s Reference
Published by
Wiley Publishing, Inc
10475 Crosspoint Boulevard
Indianapolis,
IN 46256 www.wiley.com Copyright c 2004 by Patricia Cardoza, Teresa Hennig, Armen Stein, Graham Seach. All rights reserved. Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada eISBN:
0-7645-7166-4 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax
(978) 646-8700. Requests to the Publisher for permission should be addressed to the Legal Department,
Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-mail: permcoordinator@wiley.com.
LIMIT
OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS
OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WAR- RANTIES,
INCLUDING WITHOUT LIMITATION, WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE.
NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUB-
LISHER
IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES.
IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL
BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZA- TION
OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE
OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUB- LISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS
IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTER- NET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and service or to obtain technical support, please contact our Customer Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Trademarks:
Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the
United States and other countries and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
To my husband Rob, together we can climb mountains. To my parents, who’ve given
me the foundation to succeed in life; I love you.—Patricia To my family, for their unwavering love and encouragement. To the PNWADG, for the privilege of leading such a great group of developers.
—Teresa
I dedicate this book (or at least my chapters) to my beautiful wife Julie-Anne, for carrying the world on her shoulders so I could work uninterrupted, and for her unfailing
support, encouragement, and sacrifice, despite illness and personal
hardship.And to my children, Madeleine and Eli, who tried to understand why Daddy couldn’t spend so much time with them. I am indeed a lucky man.
—Graham
Credits Authors Editorial Manager
Patricia Kathryn Cardoza Malm
Teresa Hennig
Vice
Armen Stein President & Executive Group Publisher
Graham Richard Seach Swadley
Executive Vice Acquisitions Editor President and Executive Publisher
Robert Robert Elliott Ipsen
Development Vice
Editor President and Publisher
Eileen Joseph Bien Calabro
B. Wikert
Production Executive Editor Editorial Director
Angela Mary Smith Bednarek
Copy Proofreading Editor and Indexing
TechBooks TECHBOOKS Production Services
Senior Production Manager
Fred Bernardi
About the Authors Authors
Patricia Cardoza is an Exchange and Outlook Applications developer, writer, and Microsoft Outlook MVP.
Patricia currently serves as Exchange Administrator and lead developer for Pacific Southwest Container, a large manufacturing company. She has authored two other books, Special Edition Using Microsoft Office
Outlook
2003 and Absolute Beginner’s Guide to Microsoft OneNote 2003. She has also written numerous articles about Outlook, Exchange, and wireless devices for a variety of journals including .NET Magazine and
Tech Republic. In her spare time, she loves to cook, read, watch movies with her husband, and spoil her three cats.
Teresa
Hennig is the owner of Eade.com, which specializes in developing cost-effective Access applications.
Her energy and enthusiasm are complemented by her ability to quickly grasp a situation and provide a solution. Her biggest rewards are being a partner with her clients and sharing their joy in their successes. Her site, www.DatabaseAnswerSite.com, is recognized as a resource for learning about relational databases by several universities and technical support organizations.
An avid Access aficionado, Teresa is the president of the two leading Access user groups in the US northwest: the Pacific Northwest Access Developers Group (PNWADG) and the Access Special Interest Group.
She is also dedicated to helping the Spinal Cord Society raise money to find a cure for spinal cord injuries.
And, she wishes that she had more time to enjoy dancing.
Graham
Seach is Chief Development Officer for a Sydney-based database development company, Pacific Database
(www.pacificdb.com.au). He has been developing applications in Access since version 1.0, has participated in the Microsoft Office 2003 beta program, and has presented at several Microsoft events, notably the Microsoft Office 2003 System launch in Sydney and Melbourne in 2003.
Graham holds an MCP in Access Development, master-level Brainbench certification in Access, and is recognized by Microsoft as an MVP (most valuable professional). He has received this award three times. He regularly provides worldwide Access developer support for Microsoft via the Microsoft newsgroups, and has been published in MSDN Magazine. Graham’s technical focus is now on Access and the SQL Server integration, having provided many business solutions to a wide range of government, military, and private organizations.
Armen
Stein is the owner and founder of J Street Technology, Inc., a team of database application developers in Redmond, Washington. He is President Emeritus of the Pacific Northwest Access
Developers Group, and has contributed to Access/Office/VB Advisor magazine and Smart Access. He has taught database classes at Bellevue Community College and Seattle Central Community College and also developed and taught his own 1-day training class called Access Development the J Street Way. Armen earned a business administration/computer science degree from Western Washington University, and has been developing computer applications since 1984. His other interests include activities with his family, backgammon, cheering on the Mariners, and driving his 1969 Ford Bronco in the sun. Contributors Steve
Clark is a Microsoft Access MVP, an MCP, and a Project Manager and Developer for the FMS Professional
Solutions Group (www.fmsinc.com/consulting). As a developer, he specializes in database development and has produced Access, VB(.NET), and ASP(.NET) applications for clients from all elements of business, both nationally and internationally. He earned a bachelor’s degree in computer science from the University of Cincinnati in 1994 and has been with FMS since 1998 and an Access MVP since
2001. When he’s not managing or developing, he enjoys participating in all forms of motorcycle racing.
Brian
M. Sockey is founder and president of Farsight Solutions, Inc. (DBA TeleVantage NorthWest), a Microsoft
Business Solutions partner, and value-added reseller of Artisoft TeleVantage software-based business telephone systems. Before starting TeleVantage NorthWest, Brian worked in the Developer
Support group at Microsoft, where he specialized in client/server development issues involving Microsoft
Access and SQL Server. Brian enjoys the great outdoors, theater, and good food (almost everything except blue cheese).
Randall
J. Weers, the founder and president of Procia, Inc., specializes in process and data management applications utilizing the Microsoft Office suite. His primary focus is to help people manage business processes and business rules through the appropriate application of process improvement and automation.
Randall’s experience includes everything from business process analysis to technical and training manual writing. Randall makes his home in Seattle, Washington, where he is the facilitator for IT
WorkGroups, a Puget Sound-based alliance of senior-level independent information technology professionals.
Sam
Radakovitz joined Microsoft in 1998 and was a member of the Access team for Access 2000, 2002, and 2003.
A lot of his efforts were focused on wizards and security features. For Access 2003, Sam was thoroughly engaged in the new macro security. This made it a perfect fit for him to review this book’s security chapters, especially the one on macro security. When creating Access applications, Sam enjoys going outside the box and adding a bit of creativity. So, being invited to provide applications that could demonstrate some of Access’s new features seemed like an awesome opportunity to share his ideas with other developers.
Acknowledgments
We’d like to thank all the folks at Wiley who made this book possible. Bob Elliott worked with Patricia and Teresa to build the amazing team of authors present on this book as well as to get all the mounds of paperwork straight. Eileen Bien Calabro showed incredible patience formatting, organizing, and editing our chapters. She reassured us that we could get all this done and done well, in a remarkably short time, as long as we focused. Our technical editor, Michael Stowe, tirelessly checked all of our facts and gently steered us back on course when needed. Techbooks International
Pvt. Ltd. worked incredibly hard to format all the pages and work with all of the figures in this book. Thanks everyone!
—The Group
Thanks to all who had to put up with me when I had to meet deadlines. My husband, Rob, endured many nights of takeout and several weekends when I was glued to my computer. My parents, Joe and Sally, have supported me in everything I do and I thank God for them every day.
I would not be where I am today in my career if it were not for the Microsoft Most Valuable Professional
(MVP) program. I am honored to be included in that esteemed group of professionals. Lastly,
I’d like to thank Teresa Hennig. She handled the majority of the scheduling of chapters and helped me keep all of the information for this book organized. Coordinating four authors and several contributors takes patience and dedication. Thanks Teresa for all your hard work.
—Patricia First, I’d like to thank Paul Eade for being such an incredible resource and wealth of knowledge. You are an amazing friend, and I cherish the opportunities to laugh and just be silly.
I can’t say enough about the Microsoft Access Team, including Rita Nikas. Their passion and dedication has made Access an incredibly powerful program. A special note of appreciation to Bill
Ramos, Tim Getsch, and Sanjay Jacob for investing so much of themselves into finding out what developers want, for making the ADE so awesome, and for being so responsive to all of our requests!
I also want to thank Michael Kaplan for sharing his opinions and encouragement and for doing so much for the Access groups.
To everyone I’ve met through this book . . . thank you for an amazing opportunity to enjoy a new challenge and to help Access developers! Very special thanks go to Patricia Cardoza, who seems like
Wonder Woman—balancing a career and family while writing multiple books. She not only wrote several elements, but also reviewed every chapter and helped us all in countless ways. And thanks to Randy Weers, who offered help when I needed it. Yes, work should be fun! And last thanks go to all the Mikes and Michaels. I can’t imagine a world without Michaels!
—Teresa
Acknowledgments
Needless to say, I want to first thank my wife and children for their support, encouragement, and understanding throughout a very difficult and demanding time.
I want to thank Rita Nikas, my Microsoft MVP Lead, who first made me aware of the book, and whose resolute determination to solve problems and to source much needed information will always be appreciated.
I also want to thank Mike Gunderloy, who, despite the fact that we had never met, kindly sent pages from his own book, to help me with mine; a gesture I will never forget.
Finally, I would like to express my thanks to Professor Roger Box of Charles Sturt University, who gave me a 2-week extension on my final assignment, so I could make a book deadline.
—Graham
I would like to acknowledge the encouragement and support from my wife, Lori, and kids, Lauren and Jonathan.
—Armen I’m glad that I could help Randy and Teresa. It is cool to feature some of my work on the book’s Web site. I want to thank my girlfriend Denice and my parents for putting up with my long hours of work and extra work! Without everyone’s support and understanding my daily life would be much more difficult!
—Steve My thanks to Teresa Hennig for giving me the opportunity to contribute to this book and for cracking the whip when I was struggling to keep moving forward. My deep appreciation to Sam Radakovitz for the invaluable insight into the new security features of Access. Thanks also to the members in IT Workgroups who helped me deliver a better picture for the Access Security model.
And most of all, in loving memory of my wife Lisa, I dedicate my efforts on this book.
—Randall Contents About vii the Authors
Acknowledgments ix Foreword xxiii Introduction
1 Chapter 7 1: Introduction to Microsoft Access
Why
7 Use Microsoft Access? Is
8 Access the Only Database I’ll Ever Need? Microsoft
8 Access MSDE
8 SQL
9 Server Automating
10 Microsoft Access Without VBA Code The
10 Database Wizard Creating
13 a Switchboard for Your Database Begin
14 at the Beginning Create
19 a Switchboard through the Switchboard Manager Add
20 and Configure Controls Using Wizards Building
21 Automation into Your Project Using
22 Expression Builder Using 23 the Macro Builder
Using 24 the Code Builder
Summary
25 Chapter 27 2: Access, VBA, and Macros
VBA 27 within Access
Writing
27 Code within Modules
VBA 29 versus Macros in Access
Macros 30 in Access 2003
Advantages 34 to Using VBA over Macros
Summary
35 Chapter 37 3: New Features in Access 2003 (and 2002)
Easy
37 Upgrading Database
38 Structure and Management Tools for Developers
Contents
66 Import Information From a SharePoint Server
61 AutoCorrect Options Buttons
62 Better Accessibility
62 XML and Access
62 Relating
XML to HTML
63 The Advantages of XML
64 Using Access 2003 with SharePoint Services
66 Export Information to a SharePoint Server
67 Access Developer Extensions
59 Templates
68 The Property Scanner
69 The Custom Startup Wizard
69 The Package Wizard
71 Summary
72 Chapter
73 VBA Objects
73 Objects
73
60 Smart Tags
Find Object Dependencies
38 Form/Report Error Checking
51 A Wizard for Every Occasion
40 Propagate Field Properties
42 Customize SQL Font
43 Get Context-Sensitive SQL Help
44 Backup Database/Project
46 Sorting Option on Lookup Wizard
47 Copy and Paste Linked Table as Local Table
47 Notable Mention
49 New Wizards and Builders and Managers
52 Available Builders
59 Windows
52 Managers
53 Changes to Jet
53 Service Pack 8
53 Security and Related Features
54 What Is Macro Security? And Why Are We Talking about Macros?
54 Digital Signatures
56 Expression Sandbox
58 End-User Enhancements
59 Pivot Charts
XP Theming
Contents Methods
74 Events
74 Variables 75 and VBA Syntax
Variables
75 Other
89 VBA Structures Comments
89 Line
91 Continuation Constants
93 Enums
94 Summary
95 Chapter 97 5: Using the VBA Editor
Anatomy 97 of the VBA Editor
Your
99 Access Database and VBA Project—Better Together Using
99 the Object Browser Testing
102 and Debugging VBA Code Summary
112 Chapter
113 6: Using DAO to Access Data Direct
113 Access Objects Why
114 Use DAO? Referring
116 to DAO Objects Default
117 Collection Items The
118 DBEngine Object The
118 Workspaces Collection The
122 Errors Collection The
123 Databases Collection The
128 Connections Collection DAO
129 Object Properties DAO
129 Property Types Creating
134 Schema Objects with DAO Managing
142 Jet Security with DAO Creating
143 Security Objects Managing
143 Users and Groups Managing
148 Passwords Managing
148 Permissions Data
152 Access with DAO Working
153 with QueryDefs Working
157 with Recordsets Filtering
159 and Ordering Recordsets Contents Navigating Recordsets
162 Bookmarks and Recordset Clones
211 The ADOX Object Model
197 Editing Data with Recordsets
200 Persistent Recordsets
201 Creating Schema Recordsets
206 Using ADO Events
209 Testing the State Property
210 Creating Schema Objects with ADOX
211 Working with Queries (Views)
196 Navigating Recordsets
212 Creating Tables and Columns
213 Creating Indexes
215 Creating Relations
217 Managing Jet Security with ADO
218 Creating Groups and Users
218 Managing Permissions
219 Summary
196 Finding Records
Referring to Recordset Columns 195 Filtering and Ordering Recordsets
166 Finding Records
179 Specifying a Cursor Location
169 Working with Recordsets
171 Summary
175 Chapter 7: Using ADO to Access Data
177 Ambiguous References
178 Referring to ADO Objects
179 Default Collection Items
179 Connecting to a Data Source
180 Rolling Your Own Connection String
Opening a Shaped Recordset 191 Verifying the Options That a Recordset Supports 194
181 Creating and Using a Data Link
182 Data Access with ADO
185 The ADO Object Model
185 Executing Action Queries
186 Creating ADO Recordsets
190 Creating a Standard Recordset
190 Creating a Recordset from a Command Object 190
220 Contents Chapter 8: Executing VBA
223 When Events Fire
245 Referring to Subforms and Subreports
239 Finding Records
239 Updating Records
240 Using Multiple Recordsets
240 Cleaning Up
244 Using
VBA in Forms and Reports 244
All About “Me” 245 Referring to Controls
246 Sizing Reports
238 Looping Through Recordsets
247 Closing Forms
247 Debugging
VBA 248
Responding to Errors 248 Investigating
Variables 250 When
Hovering Isn’t Enough—Using the Immediate Window 251 Setting Breakpoints
252 Setting Watch Values
253 Stopping Runaway Code
238 Adding Records
237 Opening Recordsets
224 Common Form Events
229 Error Handling
224 Common Control Events
225 Common Report Events
225 Asynchronous Execution
226
VBA Procedures 227
Function or Sub? 227 Public or Private?
228 Coupling and Cohesion
231 Class Modules
237 Using Recordsets
231 Using Variables
234 Using Appropriate Data Types and Sizes
234 Using Global Variables
235 Evaluating Expressions in VBA
235 If .. Then
235 Checking for Nulls
236 Nulls and Empty Strings
236 Select Case
255 Contents Stepping Through Your Code
255 Common
Chapter 10: Using VBA to Enhance Forms 281
Forms and Controls with VBA 303 Managing
On Close(): Save a Setting to the Registry 300 Creating
293 NotInList(): Adding a Value to a Combo Box at Runtime 297
Synchronizing Two Combo Boxes 292 OnChange(): Late Bind a Subform on a Tab Control
BeforeUpdate(): Performing Data Validation 291 AfterUpdate():
289 OnCurrent(): Opening Existing Records as “Read-Only” 290
Performing an Action on an Interval 288 OnClick(): Open a Form Based on Value on Current Form
Form_Open(): Passing the OpenArgs Parameter 287 OnTimer():
Event Property and Procedure Examples 287
Talking to Me? 286
Code to an Event Property 284 You
Event Properties 283 Associating
Concept Review 282 Properties 283
Handling That Sends E-mail 279 Summary 279
VBA Techniques 256 Date
Error Handling with Logging 278 Error
274 More on Absorbing an Expected Error: Example 275
270 Cleaning Up After an Error
269 Example of the Extra Resume
267 Basic Error Handling with a Twist
267 Basic Error Handling
266 Absorbing Expected Errors
Kinds of Errors: Unexpected and Expected 266 Handling Unexpected Errors
Why Use Error Handling? 265 Two
Chapter 9: VBA Error Handling 265
Summary 263
Concatenation Techniques 262
Rounding Issues 260 String
Handling 258 Handling
Multiple Form Instances 306
Contents When Not to Use VBA
354 Verbs, Nouns, and Adjectives
343 A Brief Word on Naming the Class
344 Instantiating Class Objects
344 Creating Class Methods
345 Creating Property Procedures
348 Naming Objects
354 What Does the Object Do?
355 Using Class Events
Use Classes? 342 Creating a Class Module
356 Handling Errors in Classes
361 Forms as Objects
365 Variable Scope and Lifetime
370 The Me Property
373 Creating and Using Collection Classes
374 The Three Pillars
343 Adding a Class Module to the Project
A Touch of Class 340 Why
310 Syncronized Subforms
322 Event Property and Procedure Examples 323
310 Displaying Data in a Treeview Control
311 Summary
318 Chapter 11: Enhancing Reports with VBA
319 Event Properties
319 Associating Code to an Event Property
320 You Talking to Me?
Report_Open(): Execute a Query Before Report Displays 323 Report_NoData():
Chapter 12: Creating Classes in VBA 339
What to do When There is No Data to Display 324 Section _Format(): Dynamically Display Page Numbers
326 Section_Print(): Conditional Formatting of a Text Box 327
Compute a Running Balance 328 Running
Sum Property 330 The
Report Design 331
VBA Code Behind Report 332
When Not to Use VBA 334 Summary 337
384 Contents Inheriting Interfaces
387 Instancing 391
413 Err.LastDLLError
Parameters 409 Variant
Parameters 410 Pointers to Numeric Values
411 Pointers to C Structures
411 Pointers to Arrays
411 Pointers to Functions
412 The Any Datatype
413 Distributing Applications That Reference Type Libraries and Custom DLLs 414
Parameters 408 Object
Summary 414
Chapter 14: SQL and VBA 415
Working with SQL Strings in VBA 415
Building SQL Strings with Quotes 416 Using
Single Quotes Instead of Double Quotes 417 Concatenating Long SQL Strings
418 Using SQL When Opening Forms and Reports
Parameters 409 String
Parameters 407 Handle
Summary 391
Linking Libraries in Access 2003 398
Chapter 13: Extending VBA with APIs 393
Introducing the Win32 API 393
Why Do You Need the API? 395
Introducing DLLs 397
Static Linking 397 Dynamic
Linking 398
Referencing a Library 398 Declaring
Parameters 407 Boolean
APIs 401
Understanding C Parameters 404
Signed and Unsigned Integers 405 8-Bit
Numeric Parameters 405 16-Bit
Numeric Parameters 406 32-Bit
Numeric Parameters 406 Currency
Parameters 407 Floating-Point
419 Contents Using SQL to Enhance Forms
420 Sorting on Columns
Other Applications 467 Summary 470
492 Summary
488 Methods to Create User-Level Security
487 Main Components of User-Level Security
484 User-Level Security
Securing Modules by Securing the Project 481 Compiling to Make an MDE File
VBA Code 481
481 Secure
481 Decoding an Encoded Database
480 Creating an Encoded Database
Up Shared-Level Security Using the Access Interface 475 Encoding a Database
Shared-Level Secured Back-End Databases 474 Setting
Security 474
Access Security Model Overview 471 Shared-Level
Chapter 16: Database Security 471
464 Using the Access Object Model to Pull Data from Access to
420 Selections on Index Forms
Sharing Information Is a Two-Way Street 445 Access and Outlook—Sharing Data with Others 446
422 Cascading Combo Boxes
429 Using SQL for Report Selection Criteria
431 Altering the SQL Inside Queries
436 The ReplaceOrderByClause and ReplaceWhereClause Functions
437 Summary 443
Chapter 15: Working with Office Applications 445
Working with Outlook’s Security Features 450 Creating
An Advanced Example—Creating a Graph in Access and Inserting It into PowerPoint
Other Types of Outlook Items from Access 451 Sending Information from Access to Excel
452 Provide Management with Flexible Data Access
452 Exchanging Information with Microsoft Word
460 The Easy Way—Use Access VBA to Start Your Merge
461 The Hard Way—Using VBA to Set Up Your Merge Document 462
Non-Mail Merge Operations—Sending Access Data to Word 463
529 Contents Chapter 17: Understanding Client/Server Development with VBA
531 ADP Versus MDB: Choosing the Right Client Format
574 What the Registry Controls
Custom Startup Wizard 603
Results 603
Property Scanner Search Specification 601 Search
Scanner 601
Redistributable Access Runtime 600 Property
Chapter 19: Using the ADE Tools 599
588 Summary 598
588 Putting It All together
Uses for the Built-In VBA Registry Functions 585 Using the Win32 Registry APIs
582 GetSetting 583 GetAllSettings 583 DeleteSetting 584 Typical
581 SaveSetting
576 Using the Built-In VBA Registry Functions
576 Registry Organization
575 Accessing the Registry
574 What the Registry Does
532 What Is an MDB File?
573 About the Registry
572 Chapter 18: Working with the Win32 Registry
564 Summary
564 Why Use Unbound Forms?
562 Using Unbound Forms
558 Using Persisted Recordsets
558 Binding to a Report
558 Binding to a Form, Combo Box, or List Box
555 Binding Recordsets to Objects
552 Using Access Projects
552 Using Linked Tables with MDB Files
550 Controlling the Logon Process
543 Which Format Is Right for You?
532 What Is an ADP?
Step 1: Identify the Template 605
Contents Step 2: Describe the Database and Set Startup Options
D: ADO Object Model Reference 715 Apendix
644 Sandbox Mode Limitations
646 Workarounds 646
Summary 647 Apendix
A: Upgrading to Access 2003 651 Apendix
B: References for Projects 667 Apendix
C: DAO Object Method and Property Descriptions 679 Apendix
E: The Access Object Model 731 Apendix
636 Microsoft Jet Expression Services and Sandboxes
F: Windows API Reference Information 803 Apendix
G: Naming Conventions 809 Apendix
H: Reserved Words and Special Characters 833 Apendix I: Tips and Tricks
847 Apendix J: ADO Object Argument Information 887
Apendix K: Access Wizards, Builders, and Managers 903 Apendix
Index 933
643 More about Errors and How to Fix Them
635 Using Self-Certification
605 Step 3: Define the Startup Options in the Database 607
615 Step 6: Set Installer Package Properties
Step 4: Save the Template/Create a Batch File 609
Package Wizard 610
Step 1: Identify the Template 610 Step
2: Define the Package to Create 611 Step
3: Define the Application Startup Options 613 Step 4: Add Files and Registry Keys
615 Step 5: The Installer’s Experience
618 Step 7: Save the Template/Create a Batch File 619
634 Types of Digital Signatures
Step 8: (Optional) Modify Your Install Package (MSI) 620
Summary 624
Chapter 20: Macro Security 627
Macro Security 628
What Is Macro Security? 628 Why
Have Macro Security? 628 Security
Checks Done before Opening a Database 629 Digital Signatures and Certificates
L: Windows Registry Information 909
Foreword
When Teresa told me she was writing a book on Access VBA programming, I thought she was crazy.
She’s so busy with her database consulting business and running the Pacific Northwest Access
Developers Group that I couldn’t figure out where she would find the time to write. I’m glad she and the other authors found the time. As a coordinating lead author, she worked with
Patricia and put together a team of authors that produced an excellent piece of work. This book is clear, concise, approachable, and above all, easy to understand. In addition to providing a look at the new features of Access, it provides a good overview of Macros and how you might use them to automate your Access application. I know what you’re thinking, “But this is a book on VBA, right?” Yes it is, and it jumps right into the subject in the following chapter. Here’s where it gets good. This book does a great job of progressing from fundamental topics to advanced topics. It moves smoothly from introducing VBA to automating forms and reports to working with APIs, SQL, and other Office applications. It then tackles advanced topics such as understanding client/server development, security, and working with the Windows Registry. If that weren’t enough, the book provides a set of appendixes covering a variety of important topics such as the ADO and Access object models, API reference information, naming conventions, and VBA reserved words. Clearly, there is a lot of valuable information packed into this book. If you’ve been using Access for some time and you’re just beginning to roll up your sleeves to jump into the world of code, this book is for you. If you need to hone your VBA programming skills or need ideas on how to polish your application, this book is for you as well. At the very least, you should add this book to your library of Access books, especially next to the ones by John
Viescas and Cary Prague. At most, you should have this book readily available as you work on your next project.
——Mike Hernandez nd
R
Author: , Edition Database Design for Mere Mortals
2 R Co-author:
SQL Queries for Mere Mortals
Introduction
Welcome to the Access 2003 VBA Programmer’s Reference. We wrote this book for Access users and programmers who want to increase the power of Access by adding the VBA (Microsoft Visual Basic for Applications) language. Access is Microsoft’s leading consumer relational database management system for desktop applications. It’s so popular because it’s relatively easy to learn and very powerful. With wizards and detailed help files, users can easily create tables, queries, forms, and reports after only a brief introduction.
To utilize the power of Microsoft Access more effectively, you can add VBA code to your Access databases.
By using VBA code, you can respond to application-level events, display forms and reports, manipulate toolbars, and even launch external applications or control certain aspects of Windows.
The Evolution of Access and VBA
Microsoft Access has had a rich history. Version 1.0 was the initial version of Access that ran on Windows 3.1.
It was very quickly replaced by Version 1.1, which added a few new features and fixed many of the bugs introduced in the initial version. At this point in the history of Access, no one really took Access seriously as a database; it was buggy, there were a number of limitations in its feature set, and the database community just hadn’t accepted that Microsoft could produce a quality database product.
In 1994, the first real version of Access was released: Access 2.0. Many database programmers using other software, such as FoxPro and dBase, decided to give Microsoft Access 2.0 a chance. Access 2.0 worked very well on both Windows 95 and Windows NT; however, it was missing much of the 32-bit API
(application programming interface) and couldn’t work with long filenames. Microsoft Access went through several more versions (95, 97, 2000, and 2002) before the current release, Access 2003.
Access 2003, released in October 2003, includes some additional enhancements, including the ability to open an Access 97 database without converting it to an updated format. Users of Access 2000 and Access
2002 were prompted to convert an Access 97 database to Access 2000 format before they could use the database.
This often caused problems in corporate installations where often, multiple versions of the Microsoft
Office software suite were installed on different computers or in different departments. Access 2003 can open certain Access 97 databases without converting them, thus allowing multiple versions to access the same database.
There have not been a large number of changes to VBA in Access 2003. However, the changes that have been made offer developers some distinct advantages. We’ve included an entire chapter (Chapter 3) about new features in Access 2003.
What Is VBA?
Microsoft Visual Basic for Applications (VBA) allows programmers to develop highly customized desktop applications that integrate with a variety of Microsoft and non-Microsoft programs. For example,
Introduction
all of the Microsoft Office System products support VBA. In addition, many third-party programs, such as drafting programs as well as WordPerfect, also support VBA.
VBA is actually a subset of the Visual Basic programming language and is a superset of VBScript (another in the Visual Basic family of development programs). VBA includes a robust suite of programming tools based on the Visual Basic development, arguably the world’s most popular rapid application development system. Developers can add code to tailor any VBA-enabled application to their specific business processes. A manufacturing company can use VBA within Microsoft Access to develop sophisticated inventory control and management systems with custom toolbars, a back-end database, management reports, and security. Rather than purchasing an off-the-shelf Inventory Control product, usually at a great cost and with a very limited ability to customize, developers can take a product they already have installed (Access as part of the Microsoft Office 2003 System) and build a robust application with no additional expense other than time. Once the application is in place, the developer can respond to customization requests quickly and effectively, rather than waiting for another company to work the customization into their development cycle.
You might be wondering why you should develop in VBA rather than the more robust Visual Basic 6.0 or Visual
Basic .NET. Both are robust, popular, and capable programming languages. However, using VBA within Access gives you some key benefits: First, you can take advantage of a built-in Access object library.
This means you can take full advantage of a wide variety of Access commands, including executing any command from any toolbar in Access. Second, VBA is included in all Microsoft Office
System applications. To develop in Visual Basic, you’ll need to purchase Visual Basic 6.0 or Visual Basic .NET either alone or as part of the Visual Studio or Visual Studio .NET suite. It could get very expensive if multiple developers in your organization need access to the Visual Basic development tools.
Despite the advantages of VBA, there are definitely circumstances in which you’ll want to use Visual Basic.
If you need to deploy an application to a wide variety of computers, especially those without a full installation of Microsoft Access, Visual Basic might be your best bet. We will examine the three languages in the Visual Basic family and why you might want to use each of them.
Access 2003 VBA Programmer’s Reference
This book is separated into two sections. The chapters provide tutorial information and the numerous appendices provide the reference material you’ll need to write VBA code within Access. While the chapters are designed to build upon one another to give you a detailed guide to VBA in Access, each chapter can be read and applied separately from the rest of the book.
What Does This Book Cover?
This Programmer’s Reference book covers a wide variety of programming topics. A brief introduction to
VBA is included, although this book assumes the reader has at least some basic familiarity with the VBA programming language. Likewise, an entire chapter is devoted to changes in Microsoft Office Access 2003, covering both new wizards and GUI (graphical user interface) features that previously required
VBA code, as well as the new VBA features included with Access 2003. You’ll learn how to create and name variables, how to use Data Access Object (DAO) and ActiveX Data Object (ADO) to manipulate data both within Access and within other applications, proper error handling techniques, and advanced functions such as creating classes and using APIs. There are two important chapters on Security and Macro
Security as well as a chapter on the Access Developer Extensions (ADE). Finally, we’ll explore a bit
Introduction
of the relationship between Access and SQL (Structured Query Language) Server, as well as how you can use VBA in Access to control and enhance other Office applications.
How to Use This Book
The initial chapters are written in a tutorial format with detailed examples. True to the Wrox Programmer’s
Reference standard format, we’ve included numerous reference appendices with details on the various object models you might use when writing VBA code in Access. We’ve also included a detailed primer on the Windows Registry and a listing of common API functions you might want to use in your code.
Real world examples will be given for many, if not most, of the programming topics covered in this book. Some typical topics include the following:
❑ How to hide fields on a form based on database login information. ❑ How to show or hide entire sections of reports based on information entered on a form. ❑ How to use VBA to transfer information between Access and other Office programs such as
Outlook, Word, and Excel. ❑ How to configure custom menus for your Access database applications.
Throughout the book we’ve also included tips and tricks we’ve discovered during our programming experiences.
Introductory and Background Material
Chapters 1 through 5 provide some background reference material you’ll need if you’re new to Access or
VBA.
After a detailed look at the new features in Access 2002 and 2003, we’ve provided information on the building blocks of VBA, such as objects, properties, methods, and events. An introduction to the VBA
Editor and its various debugging tools follows.
Accessing Data
After the introductory material, Chapters 6 and 7 focus on accessing data by using VBA. Both DAO and ADO provide methods for accessing data in Microsoft Access and other external data sources such as Informix and SQL Server.
Executing and Debugging