Tải bản đầy đủ (.pdf) (405 trang)

Automating Microsoft Access with VBA

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.36 MB, 405 trang )

<span class="text_page_counter">Trang 2</span><div class="page_container" data-page="2">

<b>C o n t e n t s a t a G l a n c e</b>

<b>I Laying the Foundation</b>

<b>1 Why Access? Why VBA? </b><small>. . . .</small>9

<b>2 Getting Around in the Visual Basic Editor </b><small>. . . .</small>17

<b>3 Using Variables, Constants, and Data Types </b><small>. . . .</small>33

<b>4 Using Procedures </b><small>. . . .</small>45

<b>5 Choosing the Right VBA Function </b><small>. . . .</small>57

<b>6 Using Flow-of-Control Statements </b><small>. . . .</small>91

<b>7 Working with Arrays </b><small>. . . .</small>105

<b>8 Understanding Objects </b><small>. . . .</small>113

<b>9 Understanding Scope and Lifetime </b><small>. . . .</small>131

<b>II Working with the Access User Interface10 Working with Forms </b><small>. . . .</small>145

<b>11 Analyzing the Access Event Model </b><small>. . . .</small>161

<b>12 Working with List and Combo Boxes </b><small>. . . .</small>175

<b>13 Working with Other Controls </b><small>. . . .</small>195

<b>14 Working with Reports </b><small>. . . .</small>209

<b>15 Working with the Application Collections </b> <small>. . . .</small>223

<b>III Working with Access Data16 Retrieving Data with ADO </b><small>. . . .</small>237

<b>17 Manipulating Data with ADO </b> <small>. . . .</small>253

<b>18 Creating Objects with ADOX </b><small>. . . .</small>273

<b>19 Performing Advanced Data Operations </b><small>. . . .</small>287

<b>IV Using Advanced VBA Techniques in Access20 Working with Data Files </b><small>. . . .</small>301

<b>21 Automating Other Applications </b><small>. . . .</small>313

<b>22 Working with XML Files </b><small>. . . .</small>325

<b>23 Using the Windows API </b><small>. . . .</small>337

</div><span class="text_page_counter">Trang 3</span><div class="page_container" data-page="3">

<b>Copyright© 2005 by Que Publishing</b>

All rights reserved. No part of this book shall be repro-duced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the pub-lisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages result-ing from the use of the information contained herein. International Standard Book Number: 0-7897-3244-0 Library of Congress Catalog Card Number: 2004109548 Printed in the United States of America

First Printing: September, 2004

All terms mentioned in this book that are known to be trade-marks or service trade-marks have been appropriately capitalized. Que Publishing cannot attest to the accuracy of this informa-tion. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

<b>Warning and Disclaimer</b>

Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis.

<b>Bulk Sales</b>

Que Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact

<b>U.S. Corporate and Government Sales</b>

</div><span class="text_page_counter">Trang 4</span><div class="page_container" data-page="4">

<b>Table of Contents</b>

<b>Introduction </b>

<small>. . . .</small>

<b>1</b>

Who This Book Is For <small>. . . .</small>1

What’s in This Book <small>. . . .</small>2

Conventions Used in This Book <small>. . . .</small>4

The Sample Code for This Book <small>. . . .</small>5

Contacting the Authors <small>. . . .</small>5

I LAYING THE FOUNDATION <b>1 Why Access? Why VBA? </b>

<small>. . . .</small>

<b>9</b>

Understanding the Place of Access in Office <small>. . . .</small>9

Choosing Between Access and Excel <small>. . . .</small>9

Choosing Between Access and OneNote <small>. . . .</small>11

Understanding Access Programming Choices <small>. . . .</small>11

Using Macros <small>. . . .</small>12

Using SQL <small>. . . .</small>12

Using VBA <small>. . . .</small>13

Case Study <small>. . . .</small>13

Using the TimeTrack Sample Database <small>. . . .</small>13

<b>2 Getting Around in the Visual Basic Editor </b>

<small>. . . .</small>

<b>17</b>

Your First Glance at the Visual Basic Editor <small>. . . .</small>17

Introducing the VBA Modules <small>. . . .</small>21

Entering and Running VBA Code <small>. . . .</small>22

Saving the Code <small>. . . .</small>24

Getting Help on Code <small>. . . .</small>25

Helpful Shortcuts for Entering Code <small>. . . .</small>26

</div><span class="text_page_counter">Trang 5</span><div class="page_container" data-page="5">

Establishing Good Habits in Coding <small>. . . .</small>28

Using a Naming Convention <small>. . . .</small>28

Indenting Your Code <small>. . . .</small>30

Commenting Your Code <small>. . . .</small>30

<b>3 Using Variables, Constants, and Data Types </b>

<small>. . . .</small>

<b>33</b>

Declaring Variables and Constants <small>. . . .</small>33

VBA Data Types <small>. . . .</small>39

The<small>Boolean</small>Data Type <small>. . . .</small>40

The<small>Byte</small>Data Type <small>. . . .</small>40

The<small>Currency</small>Data Type <small>. . . .</small>40

The<small>Date</small>Data Type <small>. . . .</small>41

The<small>Decimal</small>Data Type <small>. . . .</small>41

The<small>Double</small>Data Type <small>. . . .</small>41

The<small>Integer</small>Data Type <small>. . . .</small>41

The<small>Long</small>Data Type <small>. . . .</small>41

The<small>Object</small>Data Type <small>. . . .</small>41

The<small>Single</small>Data Type <small>. . . .</small>41

The<small>String</small>Data Type <small>. . . .</small>42

The<small>Variant</small>Data Type <small>. . . .</small>42

Referencing Syntax <small>. . . .</small>42

<b>4 Using Procedures </b>

<small>. . . .</small>

<b>45</b>

Understanding Procedure Types <small>. . . .</small>45

Creating and Using Sub Procedures <small>. . . .</small>45

Creating and Using Function Procedures <small>. . . .</small>47

Declaring Procedures as Public or Private <small>. . . .</small>48

Passing Arguments <small>. . . .</small>49

Using Optional Arguments and Default Values <small>. . . .</small>50

Passing Arguments by Reference <small>. . . .</small>50

Passing Arguments by Value <small>. . . .</small>51

</div><span class="text_page_counter">Trang 6</span><div class="page_container" data-page="6">

Giving a Function a Data Type <small>. . . .</small>51

Implementing Error Handling <small>. . . .</small>52

Using On Error Resume Next <small>. . . .</small>53

Using On Error Goto <small>. . . .</small>53

Debugging Code <small>. . . .</small>54

Using Run and Break Mode <small>. . . .</small>54

Single-Stepping <small>. . . .</small>55

Setting Breakpoints <small>. . . .</small>56

<b>5 Choosing the Right VBA Function </b>

<small>. . . .</small>

<b>57</b>

Introducing VBA’s Built-in Functions <small>. . . .</small>57

Converting Data Types with VBA Functions <small>. . . .</small>58

Converting to a <small>Boolean</small>Data Type <small>. . . .</small>59

Converting to a <small>Byte</small>Data Type <small>. . . .</small>60

Converting to a <small>Date</small>Data Type <small>. . . .</small>61

Converting to an <small>Integer</small>Data Type <small>. . . .</small>62

Converting to a <small>String</small>Data Type <small>. . . .</small>62

Converting to a <small>Variant</small>Data Type <small>. . . .</small>62

Converting Null Values <small>. . . .</small>63

Working with Date Functions <small>. . . .</small>65

Returning the Date <small>. . . .</small>65

Adding to and Subtracting from Dates <small>. . . .</small>66

Determining the Difference Between Two Dates <small>. . . .</small>66

Extracting Date Components <small>. . . .</small>68

Creating a Date from Individual Components <small>. . . .</small>68

Creating a Date from a String Expression <small>. . . .</small>69

Returning a Specific Date or Time Component <small>. . . .</small>69

Using Mathematical and Financial Functions <small>. . . .</small>70

The<small>Abs</small>Function <small>. . . .</small>70

The<small>Int</small>Function <small>. . . .</small>71

The<small>Rnd</small>Function <small>. . . .</small>71

The<small>Ddb</small>Function <small>. . . .</small>72

The<small>FV</small>Function <small>. . . .</small>72

The<small>IPmt</small>Function <small>. . . .</small>73

The<small>NPer</small>Function <small>. . . .</small>73

The<small>Pmt</small>Function <small>. . . .</small>73

Contents

</div><span class="text_page_counter">Trang 7</span><div class="page_container" data-page="7">

The<small>PPmt</small>Function <small>. . . .</small>73

The<small>Rate</small>Function <small>. . . .</small>74

The<small>Syd</small>Function <small>. . . .</small>74

Using String Functions <small>. . . .</small>75

The<small>Asc</small>Function <small>. . . .</small>76

The<small>Chr</small>Function <small>. . . .</small>76

The<small>Case</small>Functions <small>. . . .</small>77

The<small>Len String</small>Function <small>. . . .</small>77

The<small>Left</small>,<small>Right</small>, and<small>Mid</small>Functions <small>. . . .</small>77

The<small>Replace</small>Function <small>. . . .</small>78

The<small>Space</small>Function <small>. . . .</small>78

The<small>Split String</small>Function <small>. . . .</small>79

The<small>StrComp</small>Function <small>. . . .</small>79

The Three <small>Trimming</small>Functions <small>. . . .</small>79

Using the <small>Format</small>Function <small>. . . .</small>81

Applying User-Defined Formats <small>. . . .</small>82

Using the <small>Is</small>Functions for Flawless Processing <small>. . . .</small>85

Interacting Functions <small>. . . .</small>85

The<small>InputBox</small>Function <small>. . . .</small>86

The<small>MsgBox</small>Function <small>. . . .</small>86

Case Study <small>. . . .</small>88

Business Days <small>. . . .</small>88

<b>6 Using Flow-of-Control Statements </b>

<small>. . . .</small>

<b>91</b>

Branching and Looping <small>. . . .</small>91

Using<small>If…Then…Else . . . .</small>91

The Simple<small>If</small>Statement <small>. . . .</small>91

Creating More Complex Conditions <small>. . . .</small>92

Adding the <small>Else</small>Statement <small>. . . .</small>93

Using the <small>ElseIf</small>Statement <small>. . . .</small>93

Using<small>Select</small>Case<small>. . . .</small>94

</div><span class="text_page_counter">Trang 8</span><div class="page_container" data-page="8">

Using<small>For…Next . . . .</small>95

Looping in Reverse <small>. . . .</small>96

Using a Variable for the Loop Counter <small>. . . .</small>97

Nesting<small>For…Next</small>Loops<small>. . . .</small>98

Aborting a <small>For…Next</small>Loop <small>. . . .</small>99

Using<small>Do</small>Loops<small>. . . .</small>99

Creating a Simple <small>Do</small>Loop <small>. . . .</small>99

Varieties of the <small>Do</small>Loop<small>. . . .</small>100

Aborting a <small>Do</small>Loop<small>. . . .</small>101

Using<small>GoTo . . . .</small>101

Case Study <small>. . . .</small>102

Billing for Work in Progress <small>. . . .</small>102

<b>7 Working with Arrays </b>

<small>. . . .</small>

<b>105</b>

Introducing Array Variables <small>. . . .</small>105

Declaring an Array Variable <small>. . . .</small>105

Understanding the Array’s Index <small>. . . .</small>106

Using Option Base <small>. . . .</small>107

Working with Array Elements <small>. . . .</small>107

Defining Array Elements <small>. . . .</small>108

Referencing Array Elements <small>. . . .</small>109

Arrays with Multiple Dimensions <small>. . . .</small>110

Expanding to Dynamic Arrays <small>. . . .</small>110

About<small>ReDim . . . .</small>110

<b>8 Understanding Objects </b>

<small>. . . .</small>

<b>113</b>

Introducing Objects <small>. . . .</small>113

Digressing into the Real World <small>. . . .</small>113

An Object Example from Access <small>. . . .</small>114

Creating Objects in Code <small>. . . .</small>114

Contents

</div><span class="text_page_counter">Trang 9</span><div class="page_container" data-page="9">

Reading and Setting Properties <small>. . . .</small>116

Invoking Methods <small>. . . .</small>117

Working with Collections <small>. . . .</small>119

Working with an Object Model <small>. . . .</small>121

Using an Object Model <small>. . . .</small>121

Using References <small>. . . .</small>122

The Object Browser <small>. . . .</small>123

Creating Your Own Objects <small>. . . .</small>124

Working with Events <small>. . . .</small>126

Case Study<small>. . . .</small>128

Opening Forms and Handling Errors <small>. . . .</small>128

<b>9 Understanding Scope and Lifetime </b>

<small>. . . .</small>

<b>131</b>

What’s Scope? <small>. . . .</small>131

Procedure-Level Variables <small>. . . .</small>131

Module-Level Variables and Constants <small>. . . .</small>133

Public Variables and Constants <small>. . . .</small>134

Measuring the Lifetime of a Variable or Constant <small>. . . .</small>136

The Lifetime of a Procedure-Level Variable <small>. . . .</small>137

The Lifetime of a Module-Level Variable <small>. . . .</small>137

The Lifetime of a Public Variable <small>. . . .</small>138

Using Static Variables <small>. . . .</small>139

II WORKING WITH THE ACCESS USER INTERFACE <b>10 Working with Forms </b>

<small>. . . .</small>

<b>145</b>

Opening and Closing Forms <small>. . . .</small>145

Opening a Form <small>. . . .</small>145

Closing a Form <small>. . . .</small>146

The Form Module and Event Handling <small>. . . .</small>147

</div><span class="text_page_counter">Trang 10</span><div class="page_container" data-page="10">

Performing Common Tasks <small>. . . .</small>148

Checking for a Form’s Existence <small>. . . .</small>148

Determining Whether a Form Is Loaded <small>. . . .</small>149

Resizing a Form <small>. . . .</small>150

Passing Arguments Using OpenArgs <small>. . . .</small>151

Populating the Form <small>. . . .</small>152

Handling Errors at the Form Level <small>. . . .</small>154

Working with Multiple Form Instances <small>. . . .</small>157

Case Study <small>. . . .</small>158

Working with Two Instances of the Same Form <small>. . . .</small>158

<b>11 Analyzing the Access Event Model </b>

<small>. . . .</small>

<b>161</b>

Behind the Scenes: Data Buffers <small>. . . .</small>169

The Event Sequence for Reports <small>. . . .</small>170

Canceling Events <small>. . . .</small>171

Case Study <small>. . . .</small>172

Validating Data Before Saving It <small>. . . .</small>172

<b>12 Working with List and Combo Boxes </b>

<small>. . . .</small>

<b>175</b>

Populating a List Control <small>. . . .</small>175

A Simple Filtering List Control <small>. . . .</small>177

Adding to the List—or Not <small>. . . .</small>181

Updating a Value List <small>. . . .</small>181

Updating a Table/Query List <small>. . . .</small>183

Contents

</div><span class="text_page_counter">Trang 11</span><div class="page_container" data-page="11">

Working with Multiselect Controls <small>. . . .</small>187

Determining What’s Selected and What’s Not <small>. . . .</small>187

Considering Callback Functions <small>. . . .</small>189

Case Study <small>. . . .</small>191

Using List Box Controls as Drill-Down Controls <small>. . . .</small>191

<b>13 Working with Other Controls </b>

<small>. . . .</small>

<b>195</b>

Working with Text Boxes <small>. . . .</small>195

Key Properties of Text Boxes <small>. . . .</small>195

Tracking the Focus <small>. . . .</small>197

Working with Unbound Text Boxes <small>. . . .</small>198

Using Controls in Option Groups <small>. . . .</small>200

Working with Subforms <small>. . . .</small>202

Working with the <small>Tag</small>Property <small>. . . .</small>202

Case Study <small>. . . .</small>203

Creating a Master Viewing Form <small>. . . .</small>203

<b>14 Working with Reports </b>

<small>. . . .</small>

<b>209</b>

Introducing the Report Module and Events <small>. . . .</small>209

Opening and Closing Reports <small>. . . .</small>210

Opening a Report <small>. . . .</small>210

Closing a Report <small>. . . .</small>211

Passing Arguments Using OpenArgs <small>. . . .</small>212

Populating the Report <small>. . . .</small>213

Applying a Filter and Sort Order <small>. . . .</small>214

Handling Report-Level Errors <small>. . . .</small>215

What to Do When There’s No Data <small>. . . .</small>217

Using VBA to Determine Group Properties <small>. . . .</small>218

Case Study <small>. . . .</small>220

Adding a Daily Report <small>. . . .</small>220

</div><span class="text_page_counter">Trang 12</span><div class="page_container" data-page="12">

<b>15 Working with the Application Collections </b>

<small>. . . .</small>

<b>223</b>

Investigating the Application Collections <small>. . . .</small>223

Retrieving Lists of Objects <small>. . . .</small>225

Working with Object Properties <small>. . . .</small>226

Programmatically Determining Dependencies <small>. . . .</small>229

Case Study <small>. . . .</small>232

Enhancing the Master Form <small>. . . .</small>232

III WORKING WITH ACCESS DATA <b>16 Retrieving Data with ADO </b>

<small>. . . .</small>

<b>237</b>

What’s ADO and Why Do You Need It? <small>. . . .</small>237

The ADO Object Model <small>. . . .</small>237

Using the ADO Connection Object <small>. . . .</small>238

Opening the Connection <small>. . . .</small>239

About Connection Strings <small>. . . .</small>240

Closing a Connection <small>. . . .</small>242

Working with Command Objects <small>. . . .</small>242

Creating a Command Object <small>. . . .</small>243

Executing the Command Object <small>. . . .</small>243

Understanding the Different Types of Recordsets <small>. . . .</small>244

Creating and Opening a Recordset <small>. . . .</small>245

</div><span class="text_page_counter">Trang 13</span><div class="page_container" data-page="13">

<b>17 Manipulating Data with ADO </b>

<small>. . . .</small>

<b>253</b>

Moving Through a Recordset <small>. . . .</small>253

Referencing Recordset Fields <small>. . . .</small>256

Finding Data in a Recordset <small>. . . .</small>256

An Alternative to <small>Find</small>—the ADO <small>Seek</small>Method <small>. . . .</small>258

Adding Data Using a Recordset <small>. . . .</small>260

Deleting Data in a Recordset <small>. . . .</small>262

Updating Data in a Recordset <small>. . . .</small>263

Using Transactions to Commit Groups of Records—or Not <small>. . . .</small>266

Case Study<small>. . . .</small>268

Using a Recordset Object to Add Items to a Combo Box <small>. . . .</small>268

<b>18 Creating Objects with ADOX </b>

<small>. . . .</small>

<b>273</b>

Creating a New Group <small>. . . .</small>279

Creating a New User <small>. . . .</small>280

Changing Object Ownership <small>. . . .</small>281

Setting Object Permissions <small>. . . .</small>282

Case Study<small>. . . .</small>284

Creating a Data Dictionary <small>. . . .</small>284

<b>19 Performing Advanced Data Operations </b>

<small>. . . .</small>

<b>287</b>

Coding for Concurrency <small>. . . .</small>287

Understanding Concurrency <small>. . . .</small>287

Optimistic Locking in ADO <small>. . . .</small>289

Pessimistic Locking in ADO <small>. . . .</small>291

</div><span class="text_page_counter">Trang 14</span><div class="page_container" data-page="14">

Retrieving a User Recordset <small>. . . .</small>293

Using Other Schema Recordsets <small>. . . .</small>294

Case Study <small>. . . .</small>296

Using the Form Error Event to Resolve Locking Errors <small>. . . .</small>296

IV USING ADVANCED VBA TECHNIQUES IN ACCESS <b>20 Working with Data Files </b>

<small>. . . .</small>

<b>301</b>

Understanding File I/O <small>. . . .</small>301

Opening Files <small>. . . .</small>302

About<small>mode . . . .</small>302

About<small>access . . . .</small>303

About<small>locking . . . .</small>303

A Simple Open Example <small>. . . .</small>303

Reading from Files <small>. . . .</small>304

Using I/O to Number Lines in a Text File <small>. . . .</small>310

<b>21 Automating Other Applications </b>

<small>. . . .</small>

<b>313</b>

Understanding Automation <small>. . . .</small>313

Setting Object References <small>. . . .</small>314

Creating Objects in an Automation Server <small>. . . .</small>315

</div><span class="text_page_counter">Trang 15</span><div class="page_container" data-page="15">

Talking to Excel from Access <small>. . . .</small>318

Talking to Word from Access <small>. . . .</small>320

Case Study<small>. . . .</small>322

Using Excel Chart Features from Inside Access <small>. . . .</small>322

<b>22 Working with XML Files </b>

<small>. . . .</small>

<b>325</b>

An Introduction to XML <small>. . . .</small>325

Using ExportXML <small>. . . .</small>326

An Export Example <small>. . . .</small>327

Exporting a Web-Ready File <small>. . . .</small>329

Exporting Related Data <small>. . . .</small>329

Using<small>ImportXML . . . .</small>330

An Import Example <small>. . . .</small>331

Case Study<small>. . . .</small>334

Exporting Up-to-Date Project Information <small>. . . .</small>334

<b>23 Using the Windows API </b>

<small>. . . .</small>

<b>337</b>

Declaring API Calls <small>. . . .</small>337

Using API Calls <small>. . . .</small>338

API Calls That You Can Use From Access <small>. . . .</small>340

Determining Whether an Application Is Running <small>. . . .</small>340

Retrieving the Current Username <small>. . . .</small>341

Getting the Executable for a Data File <small>. . . .</small>342

Knowing When to Use the Windows API <small>. . . .</small>343

</div><span class="text_page_counter">Trang 16</span><div class="page_container" data-page="16">

V APPENDIX

<b>A Review of Access SQL </b>

<small>. . . .</small>

<b>347</b>

An Introduction to SQL <small>. . . .</small>347

SQL Structure and Syntax <small>. . . .</small>348

Retrieving with <small>SQL SELECT . . . .</small>350

The<small>SQL</small>Predicates <small>. . . .</small>350

The<small>SQL FROM</small>Clause <small>. . . .</small>351

The<small>SQL WHERE</small>Clause <small>. . . .</small>352

The<small>SQL ORDER BY</small>Clause <small>. . . .</small>353

The<small>SQL GROUP BY</small>Clause <small>. . . .</small>353

The<small>SQL HAVING</small>Clause <small>. . . .</small>354

Modifying with <small>SQL UPDATE . . . .</small>354

Deleting with <small>SQL DELETE . . . .</small>355

Appending With <small>SQL’s INSERT INTO . . . .</small>355

Making Tables With <small>SQL SELECT INTO . . . .</small>356

Creating a Crosstab Query with <small>SQL TRANSFORM . . . .</small>357

<b>Index</b>

<small>. . . .</small>

<b>359</b>

Contents

</div><span class="text_page_counter">Trang 17</span><div class="page_container" data-page="17">

<b>Mike Gunderloy is an independent developer and author who has been working with </b>

com-puters for 25 years. His experience with Microsoft Office dates back to Office 4.3, which, despite the number, was the very first version of the integrated suite. In the intervening years, he’s worked closely with the Office product team, participating in focus groups and even contributing some code to the finished product. Mike has written or contributed to more than 20 books on development topics. He’s currently the editor of the weekly

<i>Developer Central newsletter. You can reach Mike at </i><small></small>or visit his Web sites at <small></small>and <small></small>.

<b>Susan Sales Harkins is an independent consultant with an expertise in Access. With Mike,</b>

<i>Susan’s latest Office book is Upgrader’s Guide to Microsoft Office System 2003. Currently,Susan writes for a number of technology-based publishers and magazines, including Element</i>

<i>K Journals, builder.com, and devx.com. Her most recent books, also with Mike, includeExam Cram 2 ICDL and ICDL Practice questions Exam Cram 2, Absolute Beginner’s Guide toAccess 2002, and Absolute Beginner’s Guide to Access 2000, all from Que. </i>

<i>This one’s for Thomas, whose parents both worked on it—Mike Gunderloy</i>

<i>To Lexie for keeping me young and Bill for keeping me grounded—Susan Sales Harkins</i>

</div><span class="text_page_counter">Trang 18</span><div class="page_container" data-page="18">

One of the pleasant things about finishing a book manuscript is that you finally get to write one of the easy parts: the acknowledgments. Or rather, one of the nontechnical parts. It’s not easy to find the right words to thank everyone who helped make this a better book. We’ll start with Loretta Yates, who first approached us with the idea of contributing a book in a new series. We also had great help from the rest of our editorial team, Songlin Qiu and George Nedeff at Que Publishing, as well as technical editor Dana Jones. Thanks also to the production team who took the hard work that all these people did and turned it into a physical book.

Of course, if any inaccuracies or flat-out mistakes made it into print, it’s despite these fine people, not because of them. We’ve done our best to write the book that we think you want to read, and we thank you for buying a copy.

As always, Mike appreciates the forbearance of his family while he was writing yet another book. Dana managed to help run a household while pursuing her own business and tech editing my mistakes, not to mention growing a baby. Adam and Kayla continually rewarded me with smiles and hugs, when they weren’t making me a better man by testing my patience. And Thomas had the sense to gestate until the last chapter was in manuscript form.

<i>Susan would like to thank the Que folks for continuing to support great book projects and</i>

for continuing to call upon her to fulfill those projects. Most especially, Susan thanks her family for supporting her decision to work from home in her pajamas so she can grow young with her granddaughter.

</div><span class="text_page_counter">Trang 19</span><div class="page_container" data-page="19">

<i>As the reader of this book, you are our most important critic and commentator. We value</i>

your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way.

As an associate publisher for Que Publishing, I welcome your comments. You can email or write me directly to let me know what you did or didn’t like about this book--as well as what we can do to make our books better.

<i>Please note that I cannot help you with technical problems related to the topic of this book. We dohave a User Services group, however, where I will forward specific technical questions related to thebook.</i>

When you write, please be sure to include this book’s title and author as well as your name, email address, and phone number. I will carefully review your comments and share them with the author and editors who worked on the book.

For more information about this book or another Que Publishing title, visit our Web site at

<small>www.quepublishing.com</small>. Type the ISBN (0789732440) or the title of a book in the Search field to find the page you’re looking for.

</div><span class="text_page_counter">Trang 20</span><div class="page_container" data-page="20">

<i>Welcome to Automating Microsoft Access with VBA!</i>

This book is designed to build on the Access skills that you have already developed in a business set-ting, and help you take them to the next level— using a programming language to automate things you currently do manually. Access includes the Visual Basic for Applications (VBA) programming language, and even if you’ve never programmed before, you can learn how to use it to make your use of Access more productive than ever before.

<b>Who This Book Is For</b>

We’ve written this book for professionals who use Microsoft Access in a business setting. We don’t expect that you’re a software developer by profes-sion, but we do think you probably sit in front of a computer much of the day. You’ve got real work to get done, and you can’t spend all day sitting around reading a computer book. This has shaped our cov-erage. We aim to teach you the essential skills involved in automating your databases as quickly as possible, so that your time investment in this book is paid back rapidly. We’ve also tried to expose you to many different techniques. As a result, you might find that you reference some subjects more than others, but everything will be of interest to the beginning VBA developer.

This book was written using Access 2003, the ver-sion that ships as part of the Microsoft Office System 2003. But you don’t have to worry about upgrading to this latest version to use the informa-tion we’ve provided. The VBA language that you use has not changed substantially in recent years. You should be able to follow all the examples equally well with Access 2000 or Access 2002, although some things (such as toolbar icons) might look a bit different in earlier versions.

<b>I N T R O D U C T I O N</b>

</div><span class="text_page_counter">Trang 21</span><div class="page_container" data-page="21">

<b>What’s in This Book</b>

The book has 23 chapters divided into four parts, plus one appendix.

<small>■</small> Part I, “Laying the Foundation,” teaches you the syntax and programming structures that you need to understand before you can do useful work with VBA.

Chapter 1, “Why Access? Why VBA?,” is designed to get you oriented. Access isn’t the only application in Office, and VBA isn’t the only way to program Access. By the time you finish this first chapter, you should understand why we think using VBA to auto-mate Access is a useful skill to have.

Chapter 2, “Getting Around in the Visual Basic Editor,” shows you the user interface that you use to write VBA code. We also show you some good coding practices in this chapter.

Chapter 3, “Using Variables, Constants, and Data Types” introduces the first set of basic concepts that you need to understand to write VBA code.

Chapter 4, “Using Procedures,” gives you the tools to organize your VBA code. Procedures are independent units of code that can be executed one at a time to do use-ful work. You’ll find many more procedures over the course of the book.

Chapter 5, “Choosing the Right VBA Function,” tours some of the support that VBA gives your code. Financial and date calculations, text manipulation, and mathematical functions are a few of the things that are built into VBA. Using these functions helps you get more done while writing less code of your own.

Chapter 6, “Using Flow-of-Control Statements,” demonstrates the tools that VBA pro-vides for making decisions. For example, you can write a procedure that does one thing when a number is positive and another when the number is negative.

Chapter 7, “Working with Arrays,” discusses a way to store many pieces of information in a single variable. Arrays are useful when you’re tracking a group of similar items. Chapter 8, “Understanding Objects,” covers some of the most powerful concepts in VBA programming. Objects enable you to create structures in your VBA code that rep-resent things. VBA and Access include a number of built-in objects that you can use in your code to represent things like forms open on the screen.

Chapter 9, “Understanding Scope and Lifetime,” introduces some remaining fine points of variable handling in Access.

<small>■</small> Part II, “Working with the Access User Interface,” builds on the foundation of Part I to show you how to work with the Access user interface from code. Just about anything you can do manually, from opening a form to running a query, you can also do with code. This is where VBA meets Access to provide a true automation tool, replacing and extending anything that you can do with Access macros.

Chapter 10, “Working with Forms,” shows you how to use VBA to automate Access forms. You learn how to open and close forms, open multiple copies of the same form, and pass information to a form, among other things.

</div><span class="text_page_counter">Trang 22</span><div class="page_container" data-page="22">

What’s in This Book

Chapter 11, “Analyzing the Access Event Model,” drills into event handling in Access. Events enable you to run code when something happens onscreen. For example, you can have a bit of VBA code attached to a form so that the code runs every time a data-base user opens the form.

Chapter 12, “Working with List and Combo Boxes,” shows you how to use VBA to populate and manipulate these two important controls.

Chapter 13, “Working with Other Controls,” shows you how to use VBA with a variety of other controls on Access forms. These controls include text boxes, option buttons, and subforms.

Chapter 14, “Working with Reports,” demonstrates the use of VBA code with Access reports. You have almost complete control over the data and layout of reports from code, if you know what you’re doing.

Chapter 15, “Working with the Application Collections,” tells you how to use VBA to get information about Access objects such as forms, reports, tables, and queries.

<small>■</small> Part III, “Working with Access Data,” turns from the Access user interface to the data stored in Access. Here, you learn about using the ActiveX Data Objects (ADO) library to read and change data.

Chapter 16, “Retrieving Data with ADO,” begins the process by demonstrating how to get data from tables and queries and put it into recordset objects in memory. You learn how to get just the data that your VBA code needs to work with.

Chapter 17, “Manipulating Data with ADO,” looks at the other half of the process: adding, deleting, and updating data. ADO enables you to perform all these operations easily.

Chapter 18, “Creating Objects with ADOX,” deals with a specialized area of ADO that enables you to create your own data-bearing objects. For example, you can use ADOX to create an entirely new Access table without ever touching the Access user interface. Chapter 19, “Performing Advanced Data Operations,” digs into a few more corners of ADO. This chapter is primarily about working with a database that’s used simultane-ously by more than one user.

<small>■</small> Part IV, “Using Advanced VBA Techniques in Access,” touches on some advanced VBA techniques. You might never need any of these techniques, but they show you some of the powerful operations that VBA is capable of.

Chapter 20, “Working with Data Files,” demonstrates techniques for working with data stored in regular text files. Even though Access stores its own data within databases, VBA makes it possible to work with all sorts of other files.

Chapter 21, “Automating Other Applications,” shows you how you can use VBA code in Access to manipulate applications such as Microsoft Word or Microsoft Excel. You learn how easy it is to use this technique to make use of functionality from other appli-cations.

</div><span class="text_page_counter">Trang 23</span><div class="page_container" data-page="23">

Chapter 22, “Working with XML Files,” teaches you how VBA and Access support Extensible Markup Language (XML). XML is a current darling of the software indus-try, so it’s likely that you’ll run across XML files sooner or later.

Chapter 23, “Using the Windows API,” rounds out the book. Here, you see how to use powerful functions supplied by Microsoft Windows itself to do things that are otherwise impossible.

<small>■</small> Finally, Appendix A, “Review of Access SQL,” includes a review of the SQL language used to retrieve and manipulate data in Access. Although SQL itself isn’t a part of VBA, you need to know SQL to use some of the other functions you see in this book.

<b>Conventions Used in This Book</b>

The following typographic conventions are used in this book:

<small>■</small> Code lines, commands, statements, variables, and any text you type or see onscreen appear in a <small>monospace</small>typeface.

<small>■</small> <i>Italics highlight technical terms when they’re being defined.</i>

<small>■</small> You’ll come across a lot of syntax statements where arguments are italicized and often enclosed in brackets. The italicized text values are arguments. You replace these with values that are relevant to the task at hand. Brackets denote optional arguments. Throughout the book we’ve included some helpful features to make it easier for you to learn to use VBA quickly and effectively:

Notes provide additional notes or background on VBA features.These tidbits of information can help you understand what’s going on when you run VBA code, or point you to additional resources when you want to learn more.

Cautions warn you of potentially confusing or damaging side effects to running code.This might be anything from unexpected behavior when you do things in the wrong order to a new way to lose data.

<b>C A U T I O N</b>

Tip paragraphs offer our tips and tricks for making effective use of VBA in Access 2003. If you apply the knowledge from these paragraphs, we think you’ll find VBA to be a productive language.

</div><span class="text_page_counter">Trang 24</span><div class="page_container" data-page="24">

Contacting the Authors

Many of the chapters in this book end with a case study. These case studies are extended examples that show you how to apply the tools and techniques from the chapter in a busi-ness setting. We’ve designed the case studies to help you understand why you’re learning VBA, and to provide inspiration for automating your own databases.

<b>The Sample Code for This Book</b>

We designed the case studies in this book around a sample database named TimeTrack. TimeTrack starts the book as a very simple database with no automation. It keeps track of consulting projects, employees, and hours worked for a variety of customers. You can read more about the basic structure of the database in Chapter 1.

Each chapter’s sample code is added to the TimeTrack database to produce a new version. For example, <small>TimeTrack5.mdb</small>contains all the code from the first five chapters of the book. By the time you reach the end of the book, we hope you’ll have some appreciation of what VBA automation can do for a database.

You can download all the versions of the TimeTrack database from the Que Publishing Web site at <small>www.quepublishing.com</small>. Enter this book’s ISBN (without the hyphens) in the Search box and click Search. When the book’s title is displayed, click the title to go to a page where you can download the code.

<b>Contacting the Authors</b>

One of the best things about writing a book is the opportunity to hear from readers. We can’t upgrade Office for you, but we’d be happy to hear from you if something’s not clear, or if you just want to tell us how much you liked the book. You can email Susan at

<small></small>, or Mike at <small></small>.

</div><span class="text_page_counter">Trang 26</span><div class="page_container" data-page="26">

<b>1</b>

<b>Why Access? Why VBA?</b>

<b><small>. . . .</small></b>

<b>9</b>

<b>2</b>

<b>Getting Around in the Visual Basic Editor</b>

<b><small>. . . .</small></b>

<b>17</b>

<b>3</b>

<b>Using Variables, Constants, and Data Types</b>

<b><small>. . . .</small></b>

<b>33</b>

<b>4</b>

<b>Using Procedures</b>

<b><small>. . . .</small></b>

<b>45</b>

<b>5</b>

<b>Choosing the Right VBA Function</b>

<b><small>. . . .</small></b>

<b>57</b>

<b>6</b>

<b>Using Flow-of-Control Statements</b>

<b><small>. . . .</small></b>

<b>91</b>

<b>7</b>

<b>Working with Arrays</b>

<b><small>. . . .</small></b>

<b>105</b>

</div><span class="text_page_counter">Trang 28</span><div class="page_container" data-page="28">

<i>Welcome to Automating Microsoft Access with VBA.</i>

In this book, you’ll learn how to make your Access databases much more than just a convenient place to keep track of information. Visual Basic for Applications—VBA—is the core automation lan-guage that’s built in to every copy of Microsoft Access. You’ll see how you can speed up data entry, perform complex business processes, and even send data to other Windows applications. Even if you have no prior programming experience, by the end of the book you’ll be writing code with the pros. Before we dive into automating Access, though, we’re going to take a few pages to understand the place of Access and VBA in the office automation landscape. That’s what this chapter is about. Although VBA and Access are both popular and versatile tools, they’re not the perfect tool for every job, and you need to be aware of the alternatives. Presumably you’re using (or thinking about using) Access to store information. But Microsoft Office 2003 offers three different applications that are suitable for storing information:

<small>■</small> Microsoft Office Access 2003

<small>■</small> Microsoft Office Excel 2003

<small>■</small> Microsoft Office OneNote 2003

Your first task is to choose the appropriate applica-tion for your own informaapplica-tion storage needs.

<b>Choosing Between Access and Excel</b>

The most difficult choice for many users is whether to use Excel or Access for their business information.

<b>Understanding the Place of Access in Office . .9Understanding Access Programming </b>

<b>Choices . . . .11</b>

</div><span class="text_page_counter">Trang 29</span><div class="page_container" data-page="29">

Spreadsheets have been around since before most of us were working with computers, and they offer a familiar and accessible interface for storing information. Access, on the other hand, can be a bit harder to approach; there’s a certain feeling that databases are harder to understand than spreadsheets. Microsoft encourages this separation by not including Access in the least-expensive versions of the Office suite.

Although it’s true that both Access and Excel can store information in tables with rows and columns (see Figure 1.1), there are serious differences between the two. Understanding these differences will help you decide which application is right for your information. 1

<b>Figure 1.1</b>

Tables in Access and Excel.

The big advantage that Excel has over Access is the relative simplicity of its interface. Excel is a large and complex application, but it only stores things in one place: on worksheets in a workbook. By contrast, when you first open Access, you’re faced with the database window, and no obvious place to type in your data. The many object types in Access (tables, queries, forms, reports, and so on) can also be overwhelming for beginners.

But Access offers a big advantage over Excel after you get past that initial learning curve: It takes better care of your information. For example, if you tell Access that a particular col-umn in a database table will only contain dates, it won’t let you type a customer name in that column by mistake. Excel, on the other hand, will let you type pretty much anything anywhere.

Access also understands the concept of relations between data. For example, you can tell Access what the connection is between a table of clients and a table of projects. This lets Access enforce business rules, such as the rule that each project must belong to a customer.

</div><span class="text_page_counter">Trang 30</span><div class="page_container" data-page="30">

Understanding Access Programming Choices

<b>Choosing Between Access and OneNote</b>

Microsoft also released another information-storage application with Office 2003: Microsoft Office OneNote 2003, shown in Figure 1.2. Although aimed mainly at Tablet PC users, it also offers an interesting alternative for data storage on the desktop.

OneNote is designed to offer a flexible way to record and organize all sorts of information. You can type in it, hand-write notes, paste or drag in pictures and other rich content, and even make audio recordings a part of your notes. But it imposes even less structure on your information than Excel does. If you’re having trouble figuring out how something could fit into Access or Excel because it’s too unstructured, then you should take a look at OneNote as an alternative.

<b>Understanding Access Programming Choices</b>

After you’ve settled on Access as the place where you’ll store your information, you still have decisions to make. One of these is which programming language to use with Access.

Throughout this book, we’ll assume that you already have a good understanding of the Access user interface and the basics of building a relational database. If you need to brush up on these subjects,

<i>we suggest reading Absolute Beginner’s Guide to Microsoft Office Access 2003, by Mike Gunderloy and</i>

Susan Sales Harkins (Que, 2004).

</div><span class="text_page_counter">Trang 31</span><div class="page_container" data-page="31">

VBA is not the only means available to automate your Access solutions; depending on the situation, you might also want to make use of Access macros or Structured Query Language (SQL) for some or all of your work.

<b>Using Macros</b>

You may already be familiar with the Access macro programming language, which provides a limited (though still useful) set of tools for automating database actions. For example, Figure 1.3 shows a simple macro that opens a single form. You can run this macro directly from the database container, or attach it to a button on another form.

Macros are useful but limited. We’ve seen some databases that do amazing things with macros, but if you’re a power user, you’ll soon hit their limits. In particular, macros have only a limited ability to respond to errors or other conditions out of the ordinary.

<b>Using SQL</b>

You might also have heard of Structured Query Language, more commonly called SQL. SQL is the language that Access uses to store database queries. For example, you might want to find all the Web-related projects in a database of tasks. Figure 1.4 shows an Access query to perform this task.

Although most users prefer to work with queries in design view, this isn’t how Access saves your queries. Instead, it uses SQL for this purpose. Here’s the SQL statement that corre-sponds to the query shown in Figure 1.4:

<small>SELECT Projects.*FROM Projects</small>

There’s no need to remove working macros from a database if you’ve decided to switch to VBA. Access is perfectly able to mix the two automation languages in a single database.

</div><span class="text_page_counter">Trang 32</span><div class="page_container" data-page="32">

Understanding Access Programming Choices

<b>Figure 1.4</b>

The design view of an Access query is just a pretty face atop the query’s SQL.

<b>C A S E</b>S T U DY

Although SQL isn’t a general-purpose programming language, you’ll need to understand the basics to work with Access. That’s because many automation tasks in Access involve retrieving particular data, and SQL is the way to do that.

If you’re not familiar with SQL, you’ll find a primer in Appendix A,“Review of Access SQL,” page 347.

<b>Using VBA</b>

Finally, there’s VBA, the focus of this book. VBA can automate just about any operation that you can perform in an Access database. Here are some of the things that we’ll teach you to do throughout this book with VBA:

<small>■</small> Streamline data entry on Access forms

<small>■</small> Add new items to list boxes

<small>■</small> Customize the data that appears on reports

<small>■</small> Work with data without even opening a form

<small>■</small> Automate other applications from within Access

<small>■</small> Import and export XML files

That’s just a small sample; the possibilities are nearly limitless. To demonstrate the power of VBA, we’ll start with a simple database and gradually make it more complex (and useful).

<b>Using the TimeTrack Sample Database</b>

Of course, you’ll eventually want to use the techniques that you learn from this book in your own databases. But to demonstrate them, we’re going to use a sample database named <small>TimeTrack.mdb</small>. At this point, there’s no VBA code at all in the TimeTrack database. It handles the basic activities involved in keeping track of billable time for a small software development company, but it’s pretty bare bones.

</div><span class="text_page_counter">Trang 33</span><div class="page_container" data-page="33">

When you open the database, you’ll see the Switchboard form, shown in Figure 1.5.This form provides an interface to the other four forms and the single report that make up the application.

<b>Figure 1.5</b>

The Switchboard form is the starting point for the TimeTrack application.

Clicking the Clients button will show you the list of the firm’s clients as well as the projects that are underway for each client. Figure 1.6 shows the form that displays this information.

<b>Figure 1.6</b>

You can work with both clients and projects from the clients form.

Figure 1.7 shows the Employees form, which tracks basic information for each employee who can be assigned to work on a task.

<b>Figure 1.7</b>

The Employees form dis-plays basic information on each employee.

The Projects form is central to working with projects. For each project, you can choose the appropriate client.You can also enter the various tasks that make up the project and the billing rate associated with each one, as shown in Figure 1.8.

</div><span class="text_page_counter">Trang 34</span><div class="page_container" data-page="34">

Understanding Access Programming Choices

The last form in the application, shown in Figure 1.9, tracks timeslip information. After choosing an employee and a task, you can enter the date and the number of hours worked.This ensures that those hours are properly billed to the customer.

<b>Figure 1.8</b>

Projects contain tasks, which can be billed at different rates.

<b>Figure 1.9</b>

Timeslips record billable time.

Finally, Figure 1.10 shows the Billing Report, which is used to calculate charges for a client.When you run the report, it will prompt you to select a client as well as a starting date and an ending date.

<b>Figure 1.10</b>

The Billing Report calcu-lates the amount due from a client for a period of time.

Right now, all the automation in this database is done with macros. But it won’t stay that way!

</div><span class="text_page_counter">Trang 36</span><div class="page_container" data-page="36">

<b>I N T H I S C H A P T E RGetting Around in the</b>

<b>Visual Basic Editor</b>

<b>Your First Glance at the Visual BasicEditor</b>

The Visual Basic Editor (VBE) is the interface you’ll use to write VBA code. Figure 2.1 shows the VBE window for the TimeTrack sample database. The easiest way to launch the VBE is to open Access, load the database, and then press Alt+F11. (If you’re following along with an existing database, the VBE may display some code when you first open it.)

In this chapter, we’ll introduce you to the many components you’ll be working with and even let you enter a bit of code. We won’t spend a lot of time learning about every single element, tool, and menu command in the VBE—you’ll learn about them later by actually using them as you produce example code. For now, just familiarize yourself with the development environment so you’ll be on friendly ground later.

<b>Your First Glance at the Visual Basic Editor . .17Introducing the VBA Modules . . . .21Entering and Running VBA Code . . . .22Getting Help on Code . . . .25Establishing Good Habits in Coding . . . .28</b>

</div><span class="text_page_counter">Trang 37</span><div class="page_container" data-page="37">

Table 2.1 describes the tools on the VBE’s standard toolbar, which is shown in Figure 2.1. These are the tools you’ll use most of the time.

<b>Figure 2.1</b>

Welcome to the Access Visual Basic Editor.

<small>Project Icon</small>

<small>Toggle FoldersView Code</small>

<small>View Object</small>

Individual windows in the VBE are dockable, just like most menus and toolbars. Double-click the title bar of a window to toggle docked and floating.

By default, the VBE displays the following components:

<small>■</small> The menu is the default menu.

<small>■</small> The Standard toolbar is the default toolbar.

<small>■</small> Project Explorer displays a hierarchical list of the items contained and referenced in the

</div><span class="text_page_counter">Trang 38</span><div class="page_container" data-page="38">

<small>View Microsoft Office Access Displays the Access 2003 window without closing the Alt+F11View, Microsoft Office AccessVBE window.</small>

<small>Insert ModuleCreates a new and empty module. Choose a module type Insert, Modulefrom the tool’s drop-down list.</small>

<small>FindSearches for a specific word or phrase in the module.Ctrl+FEdit, FindUndoCancels the last keyboard stroke or the last mouse </small>

<small>Run Sub/ UserFormExecutes the current procedure or continues execution F5Run, Run Sub/UserFormafter a procedure has been paused by a break condition.</small>

<small>ResetTerminates a procedure and reinitializes all variables Shift+F5Run, Resetto their default values.</small>

<small>Project ExplorerOpens the Project Explorer.Ctrl+RView, Project Explorer</small>

</div><span class="text_page_counter">Trang 39</span><div class="page_container" data-page="39">

Other tools are available on the three additional toolbars, two of which are shown in Figures 2.2 and 2.3. You’ll learn more about the tools on these toolbars as you work through the examples in this book. A fourth toolbar, UserForm, is available, but we won’t cover UserForms or the toolbar in this book.

We won’t be using UserForms because Access has its own forms, with which you should already be familiar. Access forms are more powerful and flexible than UserForms.Why, then, do UserForms even exist? The answer is that the VBE, and VBA itself, are shared components.You’ll find VBA imple-mented in dozens of software packages, including other Microsoft Office applications, Autodesk’s AutoCAD drawing package, Peachtree Office Accounting, and more.These other products, which lack their own forms interface, benefit from the inclusion of UserForms in VBA.

<b>Figure 2.2</b>

Debug tools help you quickly squash bugs in

To display a toolbar, choose View, Toolbars and click the appropriate toolbar item: Debug, Edit, or Standard. (Uncheck an item to hide the toolbar.)

</div><span class="text_page_counter">Trang 40</span><div class="page_container" data-page="40">

Introducing the VBA Modules

<b>Introducing the VBA Modules</b>

After launching the VBE, you’ll probably want to view existing code or enter new code. All VBA code is contained in one of three types of modules:

<small>■</small> Standard—Contains code that’s independent of a specific object.

<small>■</small> Object—Contains code that responds to the attached form or report. If you’re already writing event procedures, you’re doing so in these modules. Each form and report in an Access database can have its own object module.

<small>■</small> Class—Contains code that defines custom objects. You’ll learn about class modules in Chapter 8, “Understanding Objects”

To insert a standard or class module, choose Insert, Module or Insert, Class Module, respec-tively. Access responds by inserting the appropriate type module.

Figure 2.4 shows a standard module in the VBE. Notice how inserting a new module updates the contents of both the Project Explorer and the Properties window. Enter proce-dures that are independent of any objects or events in a standard module. You can use objects and events in the code, but the module itself isn’t defined by an object nor does it contain any predefined events.

<b>Figure 2.4</b>

Modules contain the VBA code that automates your database.

Object modules come with the forms or reports you create. They’re really a type of class module, but you don’t have to reinvent the wheel every time you want to add code to a form or report. These modules come with your forms and reports. The code in an object module is usually triggered by and responds to the object’s events. However, an object mod-ule can contain a procedure that’s not related to an event.

</div>

×