• Tidak ada hasil yang ditemukan

Wrox Access 2003 VBA Programmers Reference Apr 2004 ISBN 0764559036 pdf

N/A
N/A
Protected

Academic year: 2019

Membagikan "Wrox Access 2003 VBA Programmers Reference Apr 2004 ISBN 0764559036 pdf"

Copied!
985
0
0

Teks penuh

(1)
(2)

Access

2003

VBA

(3)
(4)

Access

2003

VBA

Programmer’s

Reference

Patricia Cardoza

Teresa Hennig

Graham Seach

Armen Stein

(5)

Access

2003

VBA

Programmer’s

Reference

Publishedby

Wiley Publishing, Inc.

10475CrosspointBoulevard

Indianapolis,IN46256

www.wiley.com

Copyrightc 2004byPatriciaCardoza,TeresaHennig,ArmenStein,GrahamSeach.Allrightsreserved.

PublishedbyWileyPublishing,Inc.,Indianapolis,Indiana

PublishedsimultaneouslyinCanada

eISBN:0-7645-7166-4

ManufacturedintheUnitedStatesofAmerica

10 9 8 7 6 5 4 3 2 1

Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmittedinanyform

orbyanymeans,electronic,mechanical,photocopying,recording,scanning,orotherwise,exceptas

permittedunderSection107or108ofthe1976UnitedStatesCopyrightAct,withouteithertheprior

writtenpermissionofthePublisher,orauthorizationthroughpaymentoftheappropriateper-copyfee

totheCopyrightClearanceCenter,Inc.,222RosewoodDrive,Danvers,MA01923,(978)750-8400,

fax(978)646-8700.RequeststothePublisherforpermissionshouldbeaddressedtotheLegal

Department,WileyPublishing,Inc.,10475CrosspointBlvd.,Indianapolis,IN46256,(317)572-3447,

fax(317)572-4447,E-mail:permcoordinator@wiley.com.

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THEPUBLISHER AND THE AUTHOR

MAKE NOREPRESENTATIONS ORWARRANTIES WITH RESPECT TO THEACCURACY OR

COMPLETENESSOFTHECONTENTSOFTHISWORKANDSPECIFICALLYDISCLAIMALL

WAR-RANTIES,INCLUDINGWITHOUTLIMITATION,WARRANTIESOFFITNESSFORAPARTICULAR

PURPOSE.NOWARRANTYMAYBECREATEDOREXTENDEDBYSALESORPROMOTIONAL

MATERIALS. THEADVICEANDSTRATEGIES CONTAINEDHEREINMAYNOTBESUITABLE

FOREVERYSITUATION.THISWORKISSOLDWITHTHEUNDERSTANDINGTHATTHE

PUB-LISHERISNOTENGAGEDINRENDERINGLEGAL,ACCOUNTING,OROTHERPROFESSIONAL

SERVICES.IFPROFESSIONALASSISTANCEISREQUIRED,THESERVICESOFA COMPETENT

PROFESSIONALPERSONSHOULDBESOUGHT.NEITHERTHEPUBLISHERNORTHEAUTHOR

SHALL BELIABLEFORDAMAGESARISINGHEREFROM.THEFACTTHATAN

ORGANIZA-TIONORWEBSITEISREFERREDTOINTHISWORKASACITATIONAND/ORAPOTENTIAL

SOURCEOFFURTHERINFORMATIONDOESNOTMEANTHATTHEAUTHORORTHE

PUB-LISHERENDORSESTHEINFORMATIONTHEORGANIZATIONORWEBSITEMAYPROVIDEOR

RECOMMENDATIONSITMAYMAKE.FURTHER,READERSSHOULDBEAWARETHAT

INTER-NETWEBSITESLISTEDINTHISWORKMAYHAVECHANGEDORDISAPPEAREDBETWEEN

WHENTHISWORKWASWRITTENANDWHENITISREAD.

Forgeneralinformationonourotherproductsandserviceortoobtaintechnicalsupport,please

contactourCustomerCareDepartmentwithintheU.S.at(800)762-2974,outsidetheU.S.at(317)

572-3993orfax(317)572-4002.

Wileyalsopublishesitsbooksinavarietyofelectronicformats.Somecontentthatappearsinprint

maynotbeavailableinelectronicbooks.

Trademarks: Wiley,theWileylogo,Wrox,theWroxlogo,ProgrammertoProgrammerandrelated

tradedressaretrademarksorregisteredtrademarksofJohnWiley&Sons,Inc.and/oritsaffiliatesin

theUnitedStatesandothercountriesandmaynotbeusedwithoutwrittenpermission.Allother

trademarksarethepropertyoftheirrespectiveowners.WileyPublishing,Inc.,isnotassociatedwith

(6)

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.

(7)
(8)

Credits

Authors EditorialManager

PatriciaCardoza KathrynMalm

TeresaHennig

ArmenStein VicePresident&ExecutiveGroupPublisher

GrahamSeach RichardSwadley

ExecutiveAcquisitionsEditor VicePresidentandExecutivePublisher

RobertElliott RobertIpsen

DevelopmentEditor VicePresidentandPublisher

EileenBienCalabro JosephB.Wikert

ProductionEditor ExecutiveEditorialDirector

AngelaSmith MaryBednarek

CopyEditor ProofreadingandIndexing

TechBooks TECHBOOKSProductionServices

SeniorProductionManager

(9)
(10)

About

the

Authors

Authors

PatriciaCardozaisanExchangeandOutlookApplicationsdeveloper,writer,andMicrosoftOutlookMVP.

PatriciacurrentlyservesasExchangeAdministratorandleaddeveloperforPacificSouthwestContainer,

alargemanufacturingcompany.Shehasauthoredtwootherbooks,SpecialEditionUsingMicrosoftOffice

Outlook2003andAbsoluteBeginner’sGuidetoMicrosoftOneNote2003.Shehasalsowrittennumerous

articlesaboutOutlook,Exchange,andwirelessdevicesforavarietyofjournalsincluding.NETMagazine

andTechRepublic.Inhersparetime,shelovestocook,read,watchmovieswithherhusband,andspoil

herthreecats.

TeresaHennigistheownerofEade.com,whichspecializesindevelopingcost-effectiveAccess

applications.Herenergyandenthusiasmarecomplementedbyherabilitytoquicklygraspasituation

andprovideasolution.Herbiggestrewardsarebeingapartnerwithherclientsandsharingtheirjoyin

theirsuccesses.Hersite,www.DatabaseAnswerSite.com,isrecognizedasaresourceforlearningabout

relationaldatabasesbyseveraluniversitiesandtechnicalsupportorganizations.

AnavidAccessaficionado,TeresaisthepresidentofthetwoleadingAccessusergroupsintheUS

northwest:thePacificNorthwestAccessDevelopersGroup(PNWADG)andtheAccessSpecialInterest

Group.SheisalsodedicatedtohelpingtheSpinalCordSocietyraisemoneytofindacureforspinalcord

injuries.And,shewishesthatshehadmoretimetoenjoydancing.

GrahamSeachisChiefDevelopmentOfficerforaSydney-baseddatabasedevelopmentcompany,Pacific

Database(www.pacificdb.com.au).HehasbeendevelopingapplicationsinAccesssinceversion1.0,has

participatedintheMicrosoftOffice2003betaprogram,andhaspresentedatseveralMicrosoftevents,

notablytheMicrosoftOffice2003SystemlaunchinSydneyandMelbournein2003.

GrahamholdsanMCPinAccessDevelopment,master-levelBrainbenchcertificationinAccess,andis

recognizedbyMicrosoftasanMVP(mostvaluableprofessional).Hehasreceivedthisawardthreetimes.

HeregularlyprovidesworldwideAccessdevelopersupportforMicrosoftviatheMicrosoftnewsgroups,

andhasbeenpublishedinMSDNMagazine.Graham’stechnicalfocusisnowonAccessandtheSQL

Serverintegration,havingprovidedmanybusinesssolutionstoawiderangeofgovernment,military,

andprivateorganizations.

ArmenSteinistheownerandfounderofJStreetTechnology,Inc.,ateamofdatabaseapplication

developersinRedmond,Washington.HeisPresidentEmeritusofthePacificNorthwestAccess

DevelopersGroup,andhascontributedtoAccess/Office/VBAdvisormagazineandSmartAccess. He has

taughtdatabaseclassesatBellevueCommunityCollegeandSeattleCentralCommunityCollegeandalso

developedandtaughthisown1-daytrainingclasscalledAccessDevelopmenttheJStreetWay.Armen

earnedabusinessadministration/computersciencedegreefromWesternWashingtonUniversity,and

hasbeendevelopingcomputerapplicationssince1984.Hisotherinterestsincludeactivitieswithhis

(11)

Contributors

SteveClarkisaMicrosoftAccessMVP,anMCP,andaProjectManagerandDeveloperfortheFMS

ProfessionalSolutionsGroup(www.fmsinc.com/consulting).Asadeveloper,hespecializesindatabase

developmentandhasproducedAccess,VB(.NET),andASP(.NET)applicationsforclientsfromall

elementsofbusiness,bothnationallyandinternationally.Heearnedabachelor’sdegreeincomputer

sciencefromtheUniversityofCincinnatiin1994andhasbeenwithFMSsince1998andanAccessMVP

since2001.Whenhe’snotmanagingordeveloping,heenjoysparticipatinginallformsofmotorcycle

racing.

BrianM.SockeyisfounderandpresidentofFarsightSolutions,Inc.(DBATeleVantageNorthWest),a

MicrosoftBusinessSolutionspartner,andvalue-addedresellerofArtisoftTeleVantagesoftware-based

businesstelephonesystems.BeforestartingTeleVantageNorthWest,BrianworkedintheDeveloper

SupportgroupatMicrosoft,wherehespecializedinclient/serverdevelopmentissuesinvolving

MicrosoftAccessandSQLServer.Brianenjoysthegreatoutdoors,theater,andgoodfood(almost

everythingexceptbluecheese).

RandallJ.Weers,thefounderandpresidentofProcia,Inc.,specializesinprocessanddatamanagement

applicationsutilizingtheMicrosoftOfficesuite.Hisprimaryfocusistohelppeoplemanagebusiness

processesandbusinessrulesthroughtheappropriateapplicationofprocessimprovementand

automation.Randall’sexperienceincludeseverythingfrombusinessprocessanalysistotechnicaland

trainingmanualwriting.RandallmakeshishomeinSeattle,Washington,whereheisthefacilitatorforIT

WorkGroups,aPugetSound-basedallianceofsenior-levelindependentinformationtechnology

professionals.

SamRadakovitzjoinedMicrosoftin1998andwasamemberoftheAccessteamforAccess2000,2002,and

2003.Alotofhiseffortswerefocusedonwizardsandsecurityfeatures.ForAccess2003,Samwas

thoroughlyengagedinthenewmacrosecurity.Thismadeitaperfectfitforhimtoreviewthisbook’s

securitychapters,especiallytheoneonmacrosecurity.WhencreatingAccessapplications,Samenjoys

goingoutsidetheboxandaddingabitofcreativity.So,beinginvitedtoprovideapplicationsthatcould

demonstratesomeofAccess’snewfeaturesseemedlikeanawesomeopportunitytosharehisideaswith

(12)

Acknowledgments

We’dliketothankallthefolksatWileywhomadethisbookpossible.BobElliottworkedwith

PatriciaandTeresatobuildtheamazingteamofauthorspresentonthisbookaswellastogetall

themoundsofpaperworkstraight.EileenBienCalabroshowedincrediblepatienceformatting,

organizing,andeditingourchapters.Shereassuredusthatwecouldgetallthisdoneanddone

well,inaremarkablyshorttime,aslongaswefocused.Ourtechnicaleditor,MichaelStowe,

tirelesslycheckedallofourfactsandgentlysteeredusbackoncoursewhenneeded.Techbooks

InternationalPvt.Ltd.workedincrediblyhardtoformatallthepagesandworkwithallofthe

figuresinthisbook.Thankseveryone!

—TheGroup

ThankstoallwhohadtoputupwithmewhenIhadtomeetdeadlines.Myhusband,Rob,

enduredmanynightsoftakeoutandseveralweekendswhenIwasgluedtomycomputer.My

parents,JoeandSally,havesupportedmeineverythingIdoandIthankGodforthemeveryday.

IwouldnotbewhereIamtodayinmycareerifitwerenotfortheMicrosoftMostValuable

Professional(MVP)program.Iamhonoredtobeincludedinthatesteemedgroupof

professionals.

Lastly,I’dliketothankTeresaHennig.Shehandledthemajorityoftheschedulingofchapters

andhelpedmekeepalloftheinformationforthisbookorganized.Coordinatingfourauthors

andseveralcontributorstakespatienceanddedication.ThanksTeresaforallyourhardwork.

—Patricia

First,I’dliketothankPaulEadeforbeingsuchanincredibleresourceandwealthofknowledge.

Youareanamazingfriend,andIcherishtheopportunitiestolaughandjustbesilly.

Ican’tsayenoughabouttheMicrosoftAccessTeam,includingRitaNikas.Theirpassionand

dedicationhasmadeAccessanincrediblypowerfulprogram.Aspecialnoteofappreciationto

BillRamos,TimGetsch,andSanjayJacobforinvestingsomuchofthemselvesintofindingout

whatdeveloperswant,formakingtheADEsoawesome,andforbeingsoresponsivetoallofour

requests!IalsowanttothankMichaelKaplanforsharinghisopinionsandencouragementand

fordoingsomuchfortheAccessgroups.

ToeveryoneI’vemetthroughthisbook...thankyouforanamazingopportunitytoenjoyanew

challengeandtohelpAccessdevelopers!VeryspecialthanksgotoPatriciaCardoza,whoseems

likeWonderWoman—balancingacareerandfamilywhilewritingmultiplebooks.Shenotonly

wroteseveralelements,butalsoreviewedeverychapterandhelpedusallincountlessways.

AndthankstoRandyWeers,whoofferedhelpwhenIneededit.Yes,workshouldbefun!And

lastthanksgotoalltheMikesandMichaels.Ican’timagineaworldwithoutMichaels!

(13)

Acknowledgments

Needlesstosay,Iwanttofirstthankmywifeandchildrenfortheirsupport,encouragement,and

understandingthroughoutaverydifficultanddemandingtime.

IwanttothankRitaNikas,myMicrosoftMVPLead,whofirstmademeawareofthebook,and

whoseresolutedeterminationtosolveproblemsandtosourcemuchneededinformationwill

alwaysbeappreciated.

IalsowanttothankMikeGunderloy,who,despitethefactthatwehadnevermet,kindlysent

pagesfromhisownbook,tohelpmewithmine;agestureIwillneverforget.

Finally,IwouldliketoexpressmythankstoProfessorRogerBoxofCharlesSturtUniversity,

whogavemea2-weekextensiononmyfinalassignment,soIcouldmakeabookdeadline.

—Graham

Iwouldliketoacknowledgetheencouragementandsupportfrommywife,Lori,andkids,

LaurenandJonathan.

—Armen

I’mgladthatIcouldhelpRandyandTeresa.Itiscooltofeaturesomeofmyworkonthebook’s

Website.IwanttothankmygirlfriendDeniceandmyparentsforputtingupwithmylong

hoursofworkandextrawork!Withouteveryone’ssupportandunderstandingmydailylife

wouldbemuchmoredifficult!

—Steve

MythankstoTeresaHennigforgivingmetheopportunitytocontributetothisbookandfor

crackingthewhipwhenIwasstrugglingtokeepmovingforward.MydeepappreciationtoSam

RadakovitzfortheinvaluableinsightintothenewsecurityfeaturesofAccess.Thanksalsotothe

membersinITWorkgroupswhohelpedmedeliverabetterpicturefortheAccessSecurity

model.Andmostofall,inlovingmemoryofmywifeLisa,Idedicatemyeffortsonthisbook.

—Randall

(14)

Contents

About

the

Authors

vii

Acknowledgments

ix

Foreword

xxiii

Introduction

1

Chapter

1: Introduction

to

Microsoft

Access

7

Why

Use

Microsoft

Access?

7

Is

Access

the

Only

Database

I’ll

Ever

Need?

8

MicrosoftAccess 8

MSDE 8

SQLServer 9

Automating

Microsoft

Access

Without

VBA

Code

10

TheDatabaseWizard 10

Creating

a

Switchboard

for

Your

Database

13

BeginattheBeginning 14

CreateaSwitchboardthroughtheSwitchboardManager 19

Add

and

Configure

Controls

Using

Wizards

20

Building

Automation

into

Your

Project

21

UsingExpressionBuilder 22

UsingtheMacroBuilder 23

UsingtheCodeBuilder 24

Summary

25

Chapter

2: Access,

VBA,

and

Macros

27

VBA

within

Access

27

WritingCodewithinModules 27

VBA

versus

Macros

in

Access

29

MacrosinAccess2003 30

AdvantagestoUsingVBAoverMacros 34

Summary

35

Chapter

3: New

Features

in

Access

2003

(and

2002)

37

Easy

Upgrading

37

(15)

Contents

FindObjectDependencies 38

Form/ReportErrorChecking 40

PropagateFieldProperties 42

CustomizeSQLFont 43

GetContext-SensitiveSQLHelp 44

BackupDatabase/Project 46

SortingOptiononLookupWizard 47

CopyandPasteLinkedTableasLocalTable 47

NotableMention 49

New

Wizards

and

Builders

and

Managers

51

AWizardforEveryOccasion 52

AvailableBuilders 52

Managers 53

Changes

to

Jet

53

ServicePack8 53

Security

and

Related

Features

54

WhatIsMacroSecurity?AndWhyAreWeTalkingaboutMacros? 54

DigitalSignatures 56

ExpressionSandbox 58

End-User

Enhancements

59

PivotCharts 59

WindowsXPTheming 59

Templates 60

SmartTags 61

AutoCorrectOptionsButtons 62

BetterAccessibility 62

XML

and

Access

62

RelatingXMLtoHTML 63

TheAdvantagesofXML 64

Using

Access

2003

with

SharePoint

Services

66

ExportInformationtoaSharePointServer 66

ImportInformationFromaSharePointServer 67

Access

Developer

Extensions

68

ThePropertyScanner 69

TheCustomStartupWizard 69

ThePackageWizard 71

Summary

72

Chapter

4: VBA

Basics

73

VBA

Objects

73

Objects 73

(16)

Contents

Methods 74

Events 74

Variables

and

VBA

Syntax

75

Variables 75

Other

VBA

Structures

89

Comments 89

LineContinuation 91

Constants 93

Enums 94

Summary

95

Chapter

5: Using

the

VBA

Editor

97

Anatomy

of

the

VBA

Editor

97

Your

Access

Database

and

VBA

Project—Better

Together

99

UsingtheObjectBrowser 99

TestingandDebuggingVBACode 102

Summary

112

Chapter

6: Using

DAO

to

Access

Data

113

Direct

Access

Objects

113

Why

Use

DAO?

114

Referring

to

DAO

Objects

116

DefaultCollectionItems 117

The

DBEngine

Object

118

TheWorkspacesCollection 118

TheErrorsCollection 122

The

Databases

Collection

123

The

Connections

Collection

128

DAO

Object

Properties

129

DAOPropertyTypes 129

Creating

Schema

Objects

with

DAO

134

Managing

Jet

Security

with

DAO

142

CreatingSecurityObjects 143

ManagingUsersandGroups 143

ManagingPasswords 148

ManagingPermissions 148

Data

Access

with

DAO

152

WorkingwithQueryDefs 153

WorkingwithRecordsets 157

FilteringandOrderingRecordsets 159

(17)

Contents

NavigatingRecordsets 162

BookmarksandRecordsetClones 166

FindingRecords 169

WorkingwithRecordsets 171

Summary

175

Chapter

7: Using

ADO

to

Access

Data

177

Ambiguous

References

178

Referring

to

ADO

Objects

179

DefaultCollectionItems 179

Connecting

to

a

Data

Source

179

SpecifyingaCursorLocation 180

RollingYourOwnConnectionString 181

CreatingandUsingaDataLink 182

Data

Access

with

ADO

185

TheADOObjectModel 185

ExecutingActionQueries 186

Creating

ADO

Recordsets

190

CreatingaStandardRecordset 190

CreatingaRecordsetfromaCommandObject 190

OpeningaShapedRecordset 191

VerifyingtheOptionsThataRecordsetSupports 194

ReferringtoRecordsetColumns 195

FilteringandOrderingRecordsets 196

NavigatingRecordsets 196

FindingRecords 197

EditingDatawithRecordsets 200

PersistentRecordsets 201

Creating

Schema

Recordsets

206

Using

ADO

Events

209

TestingtheStateProperty 210

Creating

Schema

Objects

with

ADOX

211

TheADOXObjectModel 211

WorkingwithQueries(Views) 212

CreatingTablesandColumns 213

CreatingIndexes 215

CreatingRelations 217

Managing

Jet

Security

with

ADO

218

CreatingGroupsandUsers 218

ManagingPermissions 219

Summary

220

(18)

Contents

Chapter

8: Executing

VBA

223

When

Events

Fire

224

CommonFormEvents 224

CommonControlEvents 225

CommonReportEvents 225

AsynchronousExecution 226

VBA

Procedures

227

FunctionorSub? 227

PublicorPrivate? 228

CouplingandCohesion 229

ErrorHandling 231

ClassModules 231

Using

Variables

234

UsingAppropriateDataTypesandSizes 234

UsingGlobalVariables 235

Evaluating

Expressions

in

VBA

235

If..Then 235

CheckingforNulls 236

NullsandEmptyStrings 236

SelectCase 237

Using

Recordsets

237

OpeningRecordsets 238

LoopingThroughRecordsets 238

AddingRecords 239

FindingRecords 239

UpdatingRecords 240

UsingMultipleRecordsets 240

CleaningUp 244

Using

VBA

in

Forms

and

Reports

244

AllAbout“Me” 245

ReferringtoControls 245

ReferringtoSubformsandSubreports 246

SizingReports 247

ClosingForms 247

Debugging

VBA

248

RespondingtoErrors 248

InvestigatingVariables 250

WhenHoveringIsn’tEnough—UsingtheImmediateWindow 251

SettingBreakpoints 252

SettingWatchValues 253

StoppingRunawayCode 255

(19)

Contents

SteppingThroughYourCode 255

CommonVBATechniques 256

DateHandling 258

HandlingRoundingIssues 260

StringConcatenationTechniques 262

Summary

263

Chapter

9: VBA

Error

Handling

265

Why

Use

Error

Handling?

265

Two

Kinds

of

Errors:

Unexpected

and

Expected

266

HandlingUnexpectedErrors 266

AbsorbingExpectedErrors 267

Basic

Error

Handling

267

Basic

Error

Handling

with

a

Twist

269

ExampleoftheExtraResume 270

Cleaning

Up

After

an

Error

274

More

on

Absorbing

an

Expected

Error:

Example

275

Error

Handling

with

Logging

278

Error

Handling

That

Sends

E-mail

279

Summary

279

Chapter

10: Using

VBA

to

Enhance

Forms

281

Concept

Review

282

Properties

283

EventProperties 283

AssociatingCodetoanEventProperty 284

YouTalkingtoMe? 286

Event

Property

and

Procedure

Examples

287

Form_Open():Passingthe OpenArgs Parameter 287 OnTimer():PerforminganActiononanInterval 288 OnClick():OpenaFormBasedonValueonCurrentForm 289 OnCurrent():OpeningExistingRecordsas“Read-Only” 290

BeforeUpdate():PerformingDataValidation 291

AfterUpdate():SynchronizingTwoComboBoxes 292

OnChange():LateBindaSubformonaTabControl 293 NotInList():AddingaValuetoaComboBoxatRuntime 297

OnClose():SaveaSettingtotheRegistry 300

CreatingFormsandControlswithVBA 303

ManagingMultipleFormInstances 306

(20)

Contents

When

Not

to

Use

VBA

310

SyncronizedSubforms 310

DisplayingDatainaTreeviewControl 311

Summary

318

Chapter

11: Enhancing

Reports

with

VBA

319

Event

Properties

319

AssociatingCodetoanEventProperty 320

You

Talking

to

Me?

322

Event

Property

and

Procedure

Examples

323

Report_Open():ExecuteaQueryBeforeReportDisplays 323 Report_NoData():WhattodoWhenThereisNoDatatoDisplay 324 Section _Format():DynamicallyDisplayPageNumbers 326 Section_Print():ConditionalFormattingofaTextBox 327

ComputeaRunningBalance 328

RunningSumProperty 330

TheReportDesign 331

VBACodeBehindReport 332

When

Not

to

Use

VBA

334

Summary

337

Chapter

12: Creating

Classes

in

VBA

339

A

Touch

of

Class

340

Why

Use

Classes?

342

Creating

a

Class

Module

343

AddingaClassModuletotheProject 343

ABriefWordonNamingtheClass 344

InstantiatingClassObjects 344

CreatingClassMethods 345

CreatingPropertyProcedures 348

Naming

Objects

354

WhatDoestheObjectDo? 354

Verbs,Nouns,andAdjectives 355

UsingClassEvents 356

HandlingErrorsinClasses 361

FormsasObjects 365

VariableScopeandLifetime 370

TheMeProperty 373

CreatingandUsingCollectionClasses 374

TheThreePillars 384

(21)

Contents

InheritingInterfaces 387

Instancing 391

Summary

391

Chapter

13: Extending

VBA

with

APIs

393

Introducing

the

Win32

API

393

WhyDoYouNeedtheAPI? 395

Introducing

DLLs

397

StaticLinking 397

DynamicLinking 398

Linking

Libraries

in

Access

2003

398

ReferencingaLibrary 398

DeclaringAPIs 401

Understanding

C

Parameters

404

SignedandUnsignedIntegers 405

8-BitNumericParameters 405

16-BitNumericParameters 406

32-BitNumericParameters 406

CurrencyParameters 407

Floating-PointParameters 407

BooleanParameters 407

HandleParameters 408

ObjectParameters 409

StringParameters 409

VariantParameters 410

PointerstoNumericValues 411

PointerstoCStructures 411

PointerstoArrays 411

PointerstoFunctions 412

TheAnyDatatype 413

Err.LastDLLError

413

Distributing

Applications

That

Reference

Type

Libraries

and

Custom

DLLs

414

Summary

414

Chapter

14: SQL

and

VBA

415

Working

with

SQL

Strings

in

VBA

415

BuildingSQLStringswithQuotes 416

UsingSingleQuotesInsteadofDoubleQuotes 417

ConcatenatingLongSQLStrings 418

Using

SQL

When

Opening

Forms

and

Reports

419

(22)

Contents

Using

SQL

to

Enhance

Forms

420

SortingonColumns 420

SelectionsonIndexForms 422

CascadingComboBoxes 429

UsingSQLforReportSelectionCriteria 431

AlteringtheSQLInsideQueries 436

The

ReplaceOrderByClause

and

ReplaceWhereClause

Functions

437

Summary

443

Chapter

15: Working

with

Office

Applications

445

Sharing

Information

Is

a

Two-Way

Street

445

Access

and

Outlook—Sharing

Data

with

Others

446

WorkingwithOutlook’sSecurityFeatures 450

CreatingOtherTypesofOutlookItemsfromAccess 451

Sending

Information

from

Access

to

Excel

452

ProvideManagementwithFlexibleDataAccess 452

Exchanging

Information

with

Microsoft

Word

460

TheEasyWay—UseAccessVBAtoStartYourMerge 461 TheHardWay—UsingVBAtoSetUpYourMergeDocument 462 Non-MailMergeOperations—SendingAccessDatatoWord 463

An

Advanced

Example—Creating

a

Graph

in

Access

and

Inserting

It

into

PowerPoint

464

Using

the

Access

Object

Model

to

Pull

Data

from

Access

to

Other

Applications

467

Summary

470

Chapter

16: Database

Security

471

Access

Security

Model

Overview

471

Shared-Level

Security

474

Shared-LevelSecuredBack-EndDatabases 474

SettingUpShared-LevelSecurityUsingtheAccessInterface 475

Encoding

a

Database

480

CreatinganEncodedDatabase 481

DecodinganEncodedDatabase 481

Secure

VBA

Code

481

SecuringModulesbySecuringtheProject 481

CompilingtoMakeanMDEFile 484

User-Level

Security

487

MainComponentsofUser-LevelSecurity 488

MethodstoCreateUser-LevelSecurity 492

Summary

529

(23)

Contents

Chapter

17: Understanding

Client/Server

Development

with

VBA

531

ADP

Versus

MDB:

Choosing

the

Right

Client

Format

532

WhatIsanMDBFile? 532

WhatIsanADP? 543

WhichFormatIsRightforYou? 550

Controlling

the

Logon

Process

552

UsingLinkedTableswithMDBFiles 552

UsingAccessProjects 555

Binding

Recordsets

to

Objects

558

BindingtoaForm,ComboBox,orListBox 558

BindingtoaReport 558

UsingPersistedRecordsets 562

Using

Unbound

Forms

564

WhyUseUnboundForms? 564

Summary

572

Chapter

18: Working

with

the

Win32

Registry

573

About

the

Registry

574

WhattheRegistryDoes 574

WhattheRegistryControls 575

AccessingtheRegistry 576

RegistryOrganization 576

Using

the

Built-In

VBA

Registry

Functions

581

SaveSetting 582

GetSetting 583

GetAllSettings 583

DeleteSetting 584

TypicalUsesfortheBuilt-InVBARegistryFunctions 585

Using

the

Win32

Registry

APIs

588

Putting

It

All

together

588

Summary

598

Chapter

19: Using

the

ADE

Tools

599

Redistributable

Access

Runtime

600

Property

Scanner

601

PropertyScannerSearchSpecification 601

SearchResults 603

Custom

Startup

Wizard

603

Step1: IdentifytheTemplate 605

(24)

Contents

Step2: DescribetheDatabaseandSetStartupOptions 605 Step3: DefinetheStartupOptionsintheDatabase 607 Step4: SavetheTemplate/CreateaBatchFile 609

Package

Wizard

610

Step1: IdentifytheTemplate 610

Step2: DefinethePackagetoCreate 611

Step3: DefinetheApplicationStartupOptions 613

Step4: AddFilesandRegistryKeys 615

Step5: TheInstaller’sExperience 615

Step6: SetInstallerPackageProperties 618

Step7: SavetheTemplate/CreateaBatchFile 619 Step8: (Optional)ModifyYourInstallPackage(MSI) 620

Summary

624

Chapter

20: Macro

Security

627

Macro

Security

628

WhatIsMacroSecurity? 628

WhyHaveMacroSecurity? 628

SecurityChecksDonebeforeOpeningaDatabase 629

Digital

Signatures

and

Certificates

634

TypesofDigitalSignatures 635

UsingSelf-Certification 636

Microsoft

Jet

Expression

Services

and

Sandboxes

643

MoreaboutErrorsandHowtoFixThem 644

SandboxModeLimitations 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

D:

ADO

Object

Model

Reference

715

Apendix

E:

The

Access

Object

Model

731

Apendix

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

L:

Windows

Registry

Information

909

Index

933

(25)
(26)

Foreword

WhenTeresatoldmeshewaswritingabookonAccessVBAprogramming,Ithoughtshewas

crazy.She’ssobusywithherdatabaseconsultingbusinessandrunningthePacificNorthwest

AccessDevelopersGroupthatIcouldn’tfigureoutwhereshewouldfindthetimetowrite.I’m

gladsheandtheotherauthorsfoundthetime.Asacoordinatingleadauthor,sheworkedwith

Patriciaandputtogetherateamofauthorsthatproducedanexcellentpieceofwork.

Thisbookisclear,concise,approachable,andaboveall,easytounderstand.Inadditionto

providingalookatthenewfeaturesofAccess,itprovidesagoodoverviewofMacrosandhow

youmightusethemtoautomateyourAccessapplication.Iknowwhatyou’rethinking,“Butthis

isabookonVBA,right?”Yesitis,anditjumpsrightintothesubjectinthefollowingchapter.

Here’swhereitgetsgood.

Thisbookdoesagreatjobofprogressingfromfundamentaltopicstoadvancedtopics.Itmoves

smoothlyfromintroducingVBAtoautomatingformsandreportstoworkingwithAPIs,SQL,

andotherOfficeapplications.Itthentacklesadvancedtopicssuchasunderstanding

client/serverdevelopment,security,andworkingwiththeWindowsRegistry.Ifthatweren’t

enough,thebookprovidesasetofappendixescoveringavarietyofimportanttopicssuchasthe

ADOandAccessobjectmodels,APIreferenceinformation,namingconventions,andVBA

reservedwords.Clearly,thereisalotofvaluableinformationpackedintothisbook.

Ifyou’vebeenusingAccessforsometimeandyou’rejustbeginningtorollupyoursleevesto

jumpintotheworldofcode,thisbookisforyou.IfyouneedtohoneyourVBAprogramming

skillsorneedideasonhowtopolishyourapplication,thisbookisforyouaswell.Atthevery

least,youshouldaddthisbooktoyourlibraryofAccessbooks,especiallynexttotheonesby

JohnViescasandCaryPrague.Atmost,youshouldhavethisbookreadilyavailableasyouwork

onyournextproject.

——MikeHernandez

Author:DatabaseDesignforMereMortalsR,

2nd Edition

(27)
(28)

Introduction

WelcometotheAccess2003VBAProgrammer’sReference.WewrotethisbookforAccessusersand

programmerswhowanttoincreasethepowerofAccessbyaddingtheVBA(MicrosoftVisualBasicfor

Applications)language.AccessisMicrosoft’sleadingconsumerrelationaldatabasemanagementsystem

fordesktopapplications.It’ssopopularbecauseit’srelativelyeasytolearnandverypowerful.With

wizardsanddetailedhelpfiles,userscaneasilycreatetables,queries,forms,andreportsafteronlyabrief

introduction.

ToutilizethepowerofMicrosoftAccessmoreeffectively,youcanaddVBAcodetoyourAccess

databases.ByusingVBAcode,youcanrespondtoapplication-levelevents,displayformsandreports,

manipulatetoolbars,andevenlaunchexternalapplicationsorcontrolcertainaspectsofWindows.

The

Evolution

of

Access

and

VBA

MicrosoftAccesshashadarichhistory.Version1.0wastheinitialversionofAccessthatranonWindows

3.1.ItwasveryquicklyreplacedbyVersion1.1,whichaddedafewnewfeaturesandfixedmanyofthe

bugsintroducedintheinitialversion.AtthispointinthehistoryofAccess,noonereallytookAccess

seriouslyasadatabase;itwasbuggy,therewereanumberoflimitationsinitsfeatureset,andthe

databasecommunityjusthadn’tacceptedthatMicrosoftcouldproduceaqualitydatabaseproduct.

In1994,thefirstrealversionofAccesswasreleased:Access2.0.Manydatabaseprogrammersusingother

software,suchasFoxProanddBase,decidedtogiveMicrosoftAccess2.0achance.Access2.0worked

verywellonbothWindows95andWindowsNT;however,itwasmissingmuchofthe32-bitAPI

(applicationprogramminginterface)andcouldn’tworkwithlongfilenames.MicrosoftAccesswent

throughseveralmoreversions(95,97,2000,and2002)beforethecurrentrelease,Access2003.

Access2003,releasedinOctober2003,includessomeadditionalenhancements,includingtheabilityto

openanAccess97databasewithoutconvertingittoanupdatedformat.UsersofAccess2000andAccess

2002werepromptedtoconvertanAccess97databasetoAccess2000formatbeforetheycouldusethe

database.Thisoftencausedproblemsincorporateinstallationswhereoften,multipleversionsofthe

MicrosoftOfficesoftwaresuitewereinstalledondifferentcomputersorindifferentdepartments.Access

2003canopencertainAccess97databaseswithoutconvertingthem,thusallowingmultipleversionsto

accessthesamedatabase.

TherehavenotbeenalargenumberofchangestoVBAinAccess2003.However,thechangesthathave

beenmadeofferdeveloperssomedistinctadvantages.We’veincludedanentirechapter(Chapter3)

aboutnewfeaturesinAccess2003.

What

Is

VBA?

MicrosoftVisualBasicforApplications(VBA)allowsprogrammerstodevelophighlycustomized

(29)

Introduction

alloftheMicrosoftOfficeSystemproductssupportVBA.Inaddition,manythird-partyprograms,such

asdraftingprogramsaswellasWordPerfect,alsosupportVBA.

VBAisactuallyasubsetoftheVisualBasicprogramminglanguageandisasupersetofVBScript(another

intheVisualBasicfamilyofdevelopmentprograms).VBAincludesarobustsuiteofprogrammingtools

basedontheVisualBasicdevelopment,arguablytheworld’smostpopularrapidapplication

developmentsystem.DeveloperscanaddcodetotailoranyVBA-enabledapplicationtotheirspecific

businessprocesses.AmanufacturingcompanycanuseVBAwithinMicrosoftAccesstodevelop

sophisticatedinventorycontrolandmanagementsystemswithcustomtoolbars,aback-enddatabase,

managementreports,andsecurity.Ratherthanpurchasinganoff-the-shelfInventoryControlproduct,

usuallyatagreatcostandwithaverylimitedabilitytocustomize,developerscantakeaproductthey

alreadyhaveinstalled(AccessaspartoftheMicrosoftOffice2003System)andbuildarobustapplication

withnoadditionalexpenseotherthantime.Oncetheapplicationisinplace,thedevelopercanrespondto

customizationrequestsquicklyandeffectively,ratherthanwaitingforanothercompanytoworkthe

customizationintotheirdevelopmentcycle.

YoumightbewonderingwhyyoushoulddevelopinVBAratherthanthemorerobustVisualBasic6.0or

VisualBasic.NET.Botharerobust,popular,andcapableprogramminglanguages.However,usingVBA

withinAccessgivesyousomekeybenefits:First,youcantakeadvantageofabuilt-inAccessobject

library.ThismeansyoucantakefulladvantageofawidevarietyofAccesscommands,including

executinganycommandfromanytoolbarinAccess.Second,VBAisincludedinallMicrosoftOffice

Systemapplications.TodevelopinVisualBasic,you’llneedtopurchaseVisualBasic6.0orVisualBasic

.NETeitheraloneoraspartoftheVisualStudioorVisualStudio.NETsuite.Itcouldgetveryexpensiveif

multipledevelopersinyourorganizationneedaccesstotheVisualBasicdevelopmenttools.

DespitetheadvantagesofVBA,therearedefinitelycircumstancesinwhichyou’llwanttouseVisual

Basic.Ifyouneedtodeployanapplicationtoawidevarietyofcomputers,especiallythosewithoutafull

installationofMicrosoftAccess,VisualBasicmightbeyourbestbet.Wewillexaminethethreelanguages

intheVisualBasicfamilyandwhyyoumightwanttouseeachofthem.

Access

2003

VBA

Programmer’s

Reference

Thisbookisseparatedintotwosections.Thechaptersprovidetutorialinformationandthenumerous

appendicesprovidethereferencematerialyou’llneedtowriteVBAcodewithinAccess.Whilethe

chaptersaredesignedtobuildupononeanothertogiveyouadetailedguidetoVBAinAccess,each

chaptercanbereadandappliedseparatelyfromtherestofthebook.

What

Does

This

Book

Cover?

ThisProgrammer’sReferencebookcoversawidevarietyofprogrammingtopics.Abriefintroductionto

VBAisincluded,althoughthisbookassumesthereaderhasatleastsomebasicfamiliaritywiththeVBA

programminglanguage.Likewise,anentirechapterisdevotedtochangesinMicrosoftOfficeAccess

2003,coveringbothnewwizardsandGUI(graphicaluserinterface)featuresthatpreviouslyrequired

VBAcode,aswellasthenewVBAfeaturesincludedwithAccess2003.You’lllearnhowtocreateand

namevariables,howtouseDataAccessObject(DAO)andActiveXDataObject(ADO)tomanipulate

databothwithinAccessandwithinotherapplications,propererrorhandlingtechniques,andadvanced

functionssuchascreatingclassesandusingAPIs.TherearetwoimportantchaptersonSecurityand

MacroSecurityaswellasachapterontheAccessDeveloperExtensions(ADE).Finally,we’llexploreabit

(30)

Introduction

oftherelationshipbetweenAccessandSQL(StructuredQueryLanguage)Server,aswellashowyoucan

useVBAinAccesstocontrolandenhanceotherOfficeapplications.

How

to

Use

This

Book

Theinitialchaptersarewritteninatutorialformatwithdetailedexamples.TruetotheWrox

Programmer’sReferencestandardformat,we’veincludednumerousreferenceappendiceswithdetails

onthevariousobjectmodelsyoumightusewhenwritingVBAcodeinAccess.We’vealsoincludeda

detailedprimerontheWindowsRegistryandalistingofcommonAPIfunctionsyoumightwanttouse

inyourcode.

Realworldexampleswillbegivenformany,ifnotmost,oftheprogrammingtopicscoveredinthisbook.

Sometypicaltopicsincludethefollowing:

❑ Howtohidefieldsonaformbasedondatabaselogininformation.

❑ Howtoshoworhideentiresectionsofreportsbasedoninformationenteredonaform.

❑ HowtouseVBAtotransferinformationbetweenAccessandotherOfficeprogramssuchas

Outlook,Word,andExcel.

❑ HowtoconfigurecustommenusforyourAccessdatabaseapplications.

Throughoutthebookwe’vealsoincludedtipsandtrickswe’vediscoveredduringourprogramming

experiences.

Introductory

and

Background

Material

Chapters1through5providesomebackgroundreferencematerialyou’llneedifyou’renewtoAccessor

VBA.AfteradetailedlookatthenewfeaturesinAccess2002and2003,we’veprovidedinformationon

thebuildingblocksofVBA,suchasobjects,properties,methods,andevents.AnintroductiontotheVBA

Editoranditsvariousdebuggingtoolsfollows.

Accessing

Data

Aftertheintroductorymaterial,Chapters6and7focusonaccessingdatabyusingVBA.BothDAOand

ADOprovidemethodsforaccessingdatainMicrosoftAccessandotherexternaldatasourcessuchas

InformixandSQLServer.

Executing

and

Debugging

Chapters8and9providedetailedinformationonexecutinganddebuggingVBAcode.Every

developmentprojectneedssomedebugging,evenifyou’reanexpertdeveloper.We’llshowyousome

easywaystodebugyourcodeaswellasprovidesometipsandtrickstomakethetediousprocessof

debuggingabiteasier.

Working

with

Access

Objects

TwoAccessobjectsinparticular,FormsandReports,canmakeheavyuseofVBA(Chapters10and11).

YoucanwriteVBAcodetorespondtoavarietyofeventsfromthecontrolsonaformorevenfromthe

formitself.Youcanwritecodetoshoworhidecertainsectionsofaformorreportinresponseto

informationenteredontheformoreventheparticularuserloggedontoWindowsatthetime.

(31)

Introduction

Advanced

VBA

Programming

Thenextthreechapters(12–14)provideinformationoncreatingclassesinVBA,usingAPIs,andusing

SQLandVBA.Theyaredesignedtogiveyouathoroughtutorialonthesesubjectssoyoucandesign

yourownclasses,implementsomecommonAPIsinyourcode,anduseSQLtoaccessdata.

Miscellaneous

Material

CallingChapters15through20miscellaneousisnotreallyfairtotheextremelythoroughcontent

presented.Chapter15showsyouhowtouseVBAtotransferinformationbetweenAccessandtheother

Officeprograms.You’lllearnhowtocreatetasksande-mailinOutlook,performamailmergeinWord,

andexportdatatoanExcelspreadsheet.We’llevenshowyouhowtotakeinformationfromAccess,

createagraph,andinsertthatgraphintoPowerPoint.

Chapter16providesadetailedstudyinsecurity.Itseemseveryweekthere’sanewsecurityholeina

computerprogram,whichcanexposeyourcomputertomaliciouscode.Whendevelopingadatabase,

youcanimplementsecurityinyourdatabasetopreventusersfromseeingthecode,oryoucaneven

preventaccesstocertaintablesorqueriesinyourdatabase.

Chapter17examinesworkingwithclient/serverdevelopmentandChapter18examinestheWindows

Registry.Next,weprovideanin-depthlookatanewsetoftools,theAccessDeveloperExtensions.These

toolshelpyouautomatemanycommontasksinAccess.

Chapter20focusesonmacrosecurity.Access2003introducessomenewconcernsrelatedtomacro

security.We’llintroduceyoutoSandboxmodeandletyouknowhowtoproperlyworkwiththesenew

securityfeatures.

Appendices

AppendixAprovidesinformationonupgradingtoAccess2003frompreviousversions.AppendixB

showsyouhowtocreateandusereferenceswithinyourVBAcode.We’veprovidedextensive

informationontheDAO,ADO,andAccessObjectModelsinAppendicesC,D,andE,respectively.

RoundingoutthemixareappendicesoncommonAPIcalls,propernamingconventions,VBAreserved

words,andtheWindowsRegistry.Finally,we’veincludedawonderfulappendixfulloftipsandtricks

youcanusetodevelopprofessionalapplications.

Other

Access/VBA

Sources

Justasnoman(orwoman)isanisland,nobookcanbeallthingstoallreaders.Nomatterhowmany

timesyoureadthisbook,itcan’ttellyouthemeaningoflifeanymorethanitcantellyoueverythingyou

needtoknowaboutVBAwithinMicrosoftAccess.Thereareseveralotherresourcesyou’llwanttoutilize

whilewritingyourVBAcode.Someofourfavoritesare:

❑ MicrosoftNewsgroups—Microsoftmaintainsanewsserver(msnews.microsoft.com)andhasa

widevarietyofAccessandVBAnewsgroupstochoosefrom.Currentlytherearemorethan25

Accessnewsgroupsforyoutochoosefrom.Theyallbeginwithmicrosoft.public.access.Youcan

accessnewsgroupsthroughanewsreadersuchasOutlookExpressorthroughtheWebat:

http://support.microsoft.com/newsgroups/default.aspx.

(32)

Introduction

❑ MVPS.ORG(http://www.mvps.org/)—Thisisyourjumping-offpointtoanumberofinteresting

offeringsbeingprovidedforyoubyafewfolksassociatedwiththeMicrosoftMostValuable

Professional(MVP)program.

❑ MicrosoftAccessSupportCenter

(http://support.microsoft.com/default.aspx?scid=fh;en-us;acc&x=16&y=16)—Thisprovidesinformationaboutcurrentissues,downloads,updates,and

ofcoursewaysofobtainingproductsupport.

❑ MicrosoftonGoogle(http://www.google.com/microsoft)—ThisharnessesthepowerofGoogle

andlimitsthesearchestoMicrosoft-relatedsites.

❑ MicrosoftDeveloperNetwork(http://msdn.microsoft.com)—TheDeveloperCenterforAccess

providesamyriadofarticlesandtutorialsonkeyissues.Youcanalsofindlinkstousergroups,

newsgroups,andothervaluableresources.

❑ MicrosoftTechNet(http://www.microsoft.com/technet)—Thissiteallowsyoutoaccess

MicrosoftKnowledgeBasearticles,securityinformation,andmanyothertechnicalarticlesand

tips.

Conventions

Used

in

This

Book

We’veusedseveraldifferentstylesoftextinthisbooktohelpyouunderstanddifferenttypesof

information.Someofthestyleswe’veusedarelistedhere:

When there’s a mission critical piece of information or a tip we’ve found particularly valuable in our development, we include it in a box such as this.

Advice,hints,andbackgroundinformationcomesinthistypeoffont.

Importantwordsorphrasesareinitalic.

Wordsthatappearonthescreen,suchasmenucommandsortoolbarbuttonsareinafontsuchas

File.

Keysthatyoupressonthekeyboard,likeCtrl,areinitalics.

Codewithinthetextisstyledlikethefollowing:For I = 1 to 10

Anyneworimportantcodeisoffsetwithshadingsimilartothefollowingsample:

SELECT TeamID, TeamName, StadiumName FROM tblFootball;

Codeyou’veseenbeforeisinthesamefont,withouttheshading,asshownhere:

Dim strText as String

(33)

Introduction

Tell

Us

What

You

Think

We’vetriedtomakethisbookascompleteaspossible.We’reallactiveprogrammersandhaveincluded

tipsandtricksthatwe’veusedinoureverydaylives.Programmingbookscanoftenbedryandboring.

We’vetriedtolivenourbookupabitwithsomeinterestingexamples.Ifyoulikedthebook(orevenif

youdidn’t),weencourageyoutosendusyourfeedback.Youcancontactusviae-mailat

support@wrox.com(besuretoincludethebook’stitle)orthroughtheWroxWebsite.

Customer

Support

We’vedoneourbesttomakesurethateverycodesampleiscomplete,debugged,andwellcommented.

However,iftherearesamplesortopicsyoujustcan’tquitegrasporneedalittlemorehelpwith,thereare

placesyoucanturn.Youcane-mailyourquestionstoWroxatsupport@wrox.com(again,besureto

includethebook’stitle)orvisittheMicrosoftNewsgroups.MostofushangaroundtheAccess

newsgroupsandwillattempttoansweryourquestionsasquicklyandcompletelyaspossible.Youcan

alsoe-mailanyofusdirectly(patricia@mvps.org,teresa@eade.com,gseach@pacificdb.com.au,and

armen@JStreetTech.com).Thanksforreading!

(34)

Introduction

to

Microsoft

Access

WhatisMicrosoftAccess?Ifyou’rereadingthisbook,hopefullyyouknowthatAccessisa

relationaldatabasemanagementsystem(RDBMS).AnRDBMSmeansthatyoucanstoredatathat’s

relatedinmultipleways.Forexample,youcanstoreatableofproductsrelatedtoatableof

customers.Eachcustomercanhavemultipleproducts.Foreachcustomer,youcanstoremultiple

shippinglocationsorbillingrecords.Abasicdatabaseisnothingmorethanacollectionofdata

that’srelated.However,databasescanbemuchmorethanjustacollectionofrelateddata.Youcan

addsophisticatedcodetoyourdatabasetodisplayonlythedatayouwantintheprecisewayyou

wantit.Youcandisplaydifferentdatatoeachuserofyourdatabase.Youcanevenwriteafront-end

programforyourdatabase,usingVisualBasicorVisualC++.

AMicrosoftAccessdatabaseconsistsofavarietyofobjectstohelpyoumanageyourdata.Tables

allowyoutostoreyourdataineasytounderstandrowsandcolumns.Queriesallowyouto

manipulatedatawithintablesanddisplayinformationfrommultipletablesintheresultset.Forms

allowyoutocreateapleasantandeasilyunderstoodgraphicaluserinterface(GUI)sothatuserscan

enterdatainyourtables.Reportsallowyoutooutputdatafromtablesandqueriesinavarietyof

differentways.Youcansortandgroupdata,createcharts,addimages,andevencustomizeareport

withprogramming.DataAccesspagesallowyoutoviewformatteddatathroughInternetExplorer.

Macrosstringaseriesofcommandstogetherandrunallofthemwithlittleornouserintervention.

Finally,modulesstoreVBAcodetofurtherautomateyourdatabase.

Why

Use

Microsoft

Access?

AskavarietyofdatabaseprogrammerswhytheythinkyoushoulduseMicrosoftAccessandyou’ll

getanswersrangingfrom“it’sthebestdarnpieceofsoftwareoutthere”to“it’sarobustpieceof

softwarethatwon’tbreakthebankanddoesn’ttakeadegreeinrocketsciencetouse.”Whilewe

don’tnecessarilythinkAccessisthebestdarnpieceofsoftwareoutthere,wedothinkit’sverygood

(35)

Chapter

1

information.WedothinkAccessisaprettydarngoodpieceofsoftware.It’srelativelyeasytouse,even

forabeginner,anditcomeswitharobustsampledatabase(Northwind)thatanewusercanplayaround

withandlearnmanyofthebasics.Newuserscanlearnalotfromsimplygoingthroughthevarious

tables,queries,forms,andreportsintheNorthwinddatabase.

TherearealsoanumberofbooksonMicrosoftAccessavailableforpurchase.Youcanbuybooksfrom

beginnertoadvancedlevelandeasilycreatesimpledatabaseswithinafewhours.Inparticular,anyofthe

followingtitleswillhelpyoulearnMicrosoftAccess2003:

Access2003Bible,CaryN.Prague,MichaelR.Irwin,JenniferReardon,ISBN:0764539868,Wiley

Publishing,Inc.

Access2003All-in-OneDeskReferenceforDummies,AlanSimpson,MargaretLevineYoung,Alison

Barrows,ISBN:0-7645-3988-4,WileyPublishing,Inc.

Forexample,youcanusedatabasestoinventoryDVDcollections,trackweeklycyclingmilesand

durations,andeventologthehoursspentonvariousprojectsattheoffice.

Is

Access

the

Only

Database

I’ll

Ever

Need?

Thesimpleanswertothisquestionisno.Accessisnottheonlydatabaseproductonthemarket,norisit

theonlydatabaseproductavailablefromMicrosoft.Therearetimeswhenyoumightwanttousea

differenttypeofdatabasesuchasSQLServerorMicrosoftDevelopmentEnvironment(MSDE).Ifyou’ve

onlyeverusedMicrosoftAccessforyourdatabaseneedsyoumightbewonderingwhyyou’dneed

anothertypeofdatabaseprogram.Well,thereareseveralreasonsthataredetailedinthefollowing

paragraphs.

Microsoft

Access

MicrosoftAccessworksverywellforsingle-userapplications.YoucangetbywithAccessformultiuser

applications;however,youneedtobeawareofhowrecord-lockingoptionsaffectyourdata.It’salso

possiblethatyou’llencounteruserswholiketoopenthedatabaseexclusively,thuslockingoutother

usersfromtheapplication.IfyouhavemultipleuserswithdifferingversionsofAccesstryingtousethe

samedatabase,you’llprobablyendupwithsomecompatibilityissuesaswell.Inadditiontothe

single-userandmultiple-userscenarios,Accessworksverywellwhenyouhavemultipleusersbuta

singlecodebasethatmakesalloftherequeststothedatabase.Forexample,afront-endapplication

writteninVisualBasiccantakeadvantageofADOtomakecallstotheback-endAccessdatabase.This

typeofapplicationworksverywellinasingle- ormultiuserenvironmentastheonlytimethedatais

touchediswhenanADOcallismadetothedatabase.

MSDE

TheMicrosoftSQLServerDesktopEngine(MSDE)isactuallyadatabaseserver,verymuchlikeSQL

Server.Infact,it’sactuallyascaled-downSQLServerinstallationaimedatdesktopenvironments.Ifyou

haveadesktopapplicationthatneedsthefeaturesofSQLServer,youcanuseMSDEinplaceofafullSQL

Serverinstallation.DesigningyourapplicationagainstMSDEisalsoagoodideaifyouthinkeventually

yourapplicationwillgrowlargeenoughtoneedthefullfeaturesofSQLServer.Ifyou’redesigninga

desktopapplicationthatneedsadatabaseandhavetheMSDEpackagethat’sincludedwithVisual

(36)

Introduction

to

Microsoft

Access

Studio,youcanfreelydistributeMSDE.TheredistributionlicenseisincludedwithVisualStudio.Youcan

alsoredistributeMSDEwiththeAccessRuntimeincludedwithAccess2003.Therearesomedistinct

advantagestoMSDE.It’smorerobust,accommodatingdatabasesupto2GBinsize.Jetdatabasesare

limitedto2GBinsize;however,databaseslargerthan1GBoftensufferperformanceissues.Itispossible

foraJetdatabasetogrowto2GB;however,ifyou’redesigningaJetdatabasethatlarge,you’llneedtobe

verycarefulwithbuildingproperindexesandbuildinginaregularcompactandrepaircycle.So,why

notuseMSDEforeverything?Well,foronething,youhavemoreadministrativeandsecurityconcerns

withMSDEthanwithAccess.MSDEisadatabaseserver.Thusitcanoftenbehaveinwaystheusers

won’tunderstand.Forexample,ifdiskspacebecomesanissue,MSDEwilloftentakeatableoffline.A

typicalcomputeruserwon’tknowhowtoremedythatsituation.

Alongwithadministrativeissues,youalsoneedtoworryaboutsecurity.Asaslightlyscaled-down

versionofSQLServer,MSDEsuffersthesamesecurityvulnerabilitiesasSQLServer.MSDEwasrecently

vulnerabletotheSQLSlammerworm.Ifyou’rewritinganapplicationthatinstallsMSDE,you’llneedto

keepontopofsecurityissuesthataffectSQLServerandMSDE.

SQL

Server

Ifyou’redesigningalarge-scaleprofessionalapplicationthatrequiresaback-enddatabase,youshould

considerusingSQLServerasyourdatabase.SQLServeristhemostrobustofthedatabaseslistedinthis

chapter,butitalsocoststhemostandhasthehighestlearningcurve.YoucannotdistributeSQLServer

freely,norcanitbeinstalledonatypicaldesktopclassmachine.SQLServerrequiresWindowsNT,

Windows2000Server,orWindows2003Server.OneoftheadvantagestobothSQLServerandMSDEis

thatcodewrittenforonewillworkequallywellwiththeother.ThetwoproductsusethesameAPIand

SQLlanguage.However,thereareseveraldistinctadvantagestoSQLServer.SQLServersupportslarger

databasesandmoreusers.Inaddition,ithasmanyfeaturesthatarenotfoundinMSDE,suchasfull-text

searching,replication,failover,andQueryAnalyzer.Fromadeveloper’sperspective,SQLServerallows

youtoscriptthecreationofadatabase.MSDEdoesn’tsupportthisfunctionality.

Ifyou’renotsurewhichtypeofdatabasetocreateforyourapplication,askyourselfthefollowing

questions:

❑ Doesyourapplicationneedtobeaccessedbymultipleusers?

❑ Doesyourapplicationneedtocreatedatabasesviacode?

❑ Willyourdatabasegrowbeyond2GB?

❑ Willyourapplicationneedreplicationorfull-textsearching?

Evenansweringthesequestionswon’ttellyouforsureeverytimewhichtypeofdatabaseyoushoulduse

foryourapplication.You’llhavetousetheanswerstothesequestionsaswellassomecommonsenseand

researchtodeterminewhichtypeofdatabaseapplicationtouse.Forexample,ifyouneedadatabasethat

promisestogrowtoaround1.5GBandneedstobeaccessedbymultipleusersonacentralserver,youcan

utilizeeitherMSDEorSQLServer.However,usingSQLServergivesyousomeaddedbenefits,including

thecapacitybeyond2GBinsizeforfuturegrowth.Ifmoneyisanissue,you’llwanttoleantowardusing

anMSDEdatabase,asthelicenseisincludedwithVisualStudio.

Whateverdatabaseyouchoose,besuretoresearchyouroptionsbeforemakingyourdecision.Ifyoudo

chooseSQLServer,you’llneedtodosomeresearchonserversizingandperformancebasedonyour

application’ssizeandnumberofusers.

(37)

Chapter

1

Automating

Microsoft

Access

Without

VBA

Code

ThisbookisaboutautomatingAccesswithVBAcode;however,noteverythingyouneedtodowithyour

databaseshouldbeaccomplishedviacode.Partofbeingagoodprogrammerisknowingwhentowrite

codeandwhentoletsomeoneelsedoitforyou.ThesomeoneelsecanoftenbeMicrosoftAccessitself.

Accessisapowerfulapplicationthatincludesavarietyofwizardsandbuilt-incommandsthatcanhelp

automateyourapplicationwithoutwritingevenonelineofcode.Thissectionwillgointosomedetail

abouthowyoucanautomateyourapplicationwithoutwritinganycodeatall.

The

Database

Wizard

Ifyouneedtocreateadatabaseanddon’tknowwheretostart,youcanusetheDatabaseWizardtocreate

severaldifferenttypesofbusinessandpersonaldatabases.Someofthedifferenttypesofdatabasesyou

cancreateinclude:

❑ Assettracking

❑ Contactmanagement

Figure 1-1

(38)

Introduction

to

Microsoft

Access

❑ Eventmanagement

❑ Inventorycontrol

❑ Orderentry

❑ Timeandbilling

TocreateanewdatabaseusingtheDatabaseWizard,openAccessandselectNewfromtheFilemenuto

displaytheTaskPane.ChooseOn my computerfromtheTemplatessectionandclickthe

Databasestabinthedialogboxthatappears(Figure1-1).

ChoosethetypeofdatabaseyouwanttocreateandclickOK.Enterthefilenameforyourdatabaseand

clickCreate.AccesswilldisplaythevariousscreensoftheDatabaseWizard.Theparticularscreensyou

seeandquestionsthewizardaskswilldependonthetypeofdatabaseyouselected.We’lldetailthesteps

forcreatingadatabaseforInventoryTracking.

Thefirstscreenyou’llseedetailsthestepsAccesstakestocreateyournewdatabase.ClickNext(see

Figure1-2).

Figure 1-2

(39)

Chapter

1

Eachdatabasetyperequiresspecifictablesandfields.Youcanchoosetoaddfieldsbeyondtherequired

fieldsbychoosingthetablefromtheleft-handcolumnandbyexaminingthefieldsintheright-hand

column.Allcheckedfieldswillbeincludedintheselectedtable.Ifyouattempttoremovearequired

field,Accesswillinformyouofthefield’srequirementandleavetheboxchecked.Whenyou’redone

manipulatingthefieldsinyourtables,clickNext(seeFigure1-3).

Figure 1-3

Choosethestyleyouwantforthevariousformsinyourdatabase.ClickNexttoconfigureastyleforthe

reportsinyourdatabase.ClickNextagainandgiveyourdatabaseatitle.Thistitlecanbedifferentfrom

thefilenameyouassignedtoyourdatabase.ClickNextandthenFinishandAccesswillbuildyour

database.

Whenthewizardcompletes,Accessdisplaysyourdatabase.Youcanthenfurthercustomizeyour

database.

Ifyouneedtocreateadatabaseandjustdon’tknowwheretostart,usingtheDatabaseWizardcanhelp yougetstarted.Evenifyoudon’tuseallofthetablesandreportsthewizardcreates,usingtheDatabase Wizardcangiveyousomeideasofwhattablesyouneedinyourdatabase.

(40)

Introduction

to

Microsoft

Access

Onceyou’vecompletedtheDatabaseWizardyou’llseetherearemanyautomaticfeaturesyoucan

utilizewithinyourdatabase.Switchboards,suchastheoneinFigure1-4,providealaunchpointfor

dataentry,reports,andgraphsyoucanusewithinyourdatabase.TheSwitchboardfortheInventory

Trackingdatabaseallowsyoutoenterdata,viewthatdata,previewreports,customizetheswitchboard,

orexitthedatabase.Youcanconfigureswitchboardstolaunchaspecificreport,openaformfordata

entry,runaqueryormacro,ordisplayasecuritywarningaboutunauthorizedaccesstothedatabase.

IftheswitchboarddesignedbytheDatabaseWizarddoesn’tmeetyourneeds,youcancreateyour

own.

Figure1-4

Creating

a

Switchboard

for

Your

Database

CreatingaSwitchboardformisassimpleascreatingaformandconfiguringtheformtolaunchwhenthe

databaseloads.Onceyou’vecreatedtheform,addsomecommandbuttonstoperformvariousactions

youthinkyourusersmightwanttoperform.We’lllookatcreatingaswitchboardfromscratchinthe

followingpages.Alongtheway,we’llusesomeoftheotherbuilt-inwizardsyoucanusetoautomate

Accesswithoutcode.

(41)

Chapter

1

Begin

at

the

Beginning

Tocreateaswitchboard,you’llfirstneedtocreateanewform.ChooseFormsfromtheAccessbarand

clicktheNewbuttontolaunchtheNew Formdialogbox.Foraswitchboardformyoudon’tneedtochoose

atableorqueryfortheform’sdatasource,justchooseDesign ViewfromthelistboxandclickOK.

Youcangiveswitchboardformsanicetitleandmaybeacoupleoflinesoftexttoserveasabrief

explanationtousers.Afteryou’veaddedtheseelementstotheform,itmightlooksimilartoFigure1-5.

Anynumberofelementscanbeaddedtotheform,includingimages,text,frames,fields,orother

graphics.Butwhatgoodisaformifitdoesn’tdoanything?

Figure 1-5

Inorderforyourformtodosomething,you’llneedtoaddcommandbuttonstotheform.Toaddanew

commandbutton,choosethecommandbuttontoolfromtheControl Toolboxandclickanywhereon

yourformtoinsertthecommandbuttonandstarttheCommandButtonWizard.Thefirstscreenyou’ll

seeinthewizard(Figure1-6)allowsyoutochoosethetypeofactiontoperform.

Wetypicallystartdesigningthedatabase’sswitchboardbyaddingtwocommandbuttons:Onetolaunch

themaindataentryform(orformsasthecasemightbe)andonetoexitthedatabase.Thefollowingsteps

(42)

Introduction

to

Microsoft

Access

Figure1-6

willcreateacommandbuttontolaunchtheMySwitchboardformfordataentry:

1.

ChooseForm OperationsfromtheCategorieslistbox.

2.

ChooseOpen FormfromtheActionslistboxandclickNext(seeFigure1-7).

3.

Accessdisplaysalistofallformsavailableinyourdatabase.Choosetheappropriateformand

clickNextagain.

4.

Youcanopentheformanddisplayallrecordsorchooseaspecificrecordtodisplay.ClickNext

tocontinue.

5.

Thenextstepinconfiguringyourcommandbuttonallowsyoutoassociatetextoranimagewith

thebutton.Inmostcases,wechoosetodisplaytextonthebuttonratherthananimage.

However,ifyouaredesigningamultilanguageapplication,youmightwanttostickwith

universallyrecognizableimages,ratherthantext.Enterthetextofthebuttoninthetextbox,as

showninFigure1-8,andclickNext.

6.

Thefinalstepinthewizardisnamingyourcommandbutton.Accesssuggestsadefaultnameof

“Command”followedbyanumber.Youshouldenterameaningfulnameforyourcommand

buttonandclickFinish.

(43)

Figure1-7

(44)

Introduction

to

Microsoft

Access

Whileit’stemptingtojustacceptthisnameandmoveon,it’sagainstallcommonprogramming recommendations.Youshouldalwaysgiveyourcommandbuttons(aswellasyourothercontrolssuchas textboxes,labels,comboboxes,andimagecontrols)ameaningfulname.Evenifyoudon’tfollow establishednamingconventions,suchascmdfrmPurchaseOrder),youshouldstillensurethenameyou givetoyourobjectsismeaningful,otherwiseyoucouldbelefteditingcodethat’salmostunreadable becausenoneofyourobjectshaverecognizablenames.Justimaginetryingtoeditcodeforacommand buttonthatlaunchesaparticularformwhenyouhave100commandbuttonsonyourformandyoucan’t

rememberwhetheryouwerelookingforCommand53orCommand91.

Youcancreatemultiplecommandbuttonsusingtheprevioussteps.Whenyou’redone,yourformmight

looksomethinglikeFigure1-9.Saveyourformandcloseit.Thenextstepincreatingyourswitchboardis

configuringyourformtolaunchwhenyoustartyourdatabase.Usethefollowingstepstoconfigurea

start-upform.

Figure 1-9

1.

ChooseStartupfromtheToolsmenu(seeFigure1-10).Thedialogboxthatisdisplayed

allowsyoutoenteratitleforyourentireapplication,specifyanapplicationicon,acustomized

menubar,andspecifyastartupform.

(45)

Chapter

1

Figure1-10

2.

Usethedrop-downboxmarkedDisplay Form/Pageandchoosetheswitchboardformyou

createdpreviously.

3.

YoucanalsochoosewhetheruserswillseetheDatabaseWindowandStatusBarorwhetherthey

willonlyseeyourcustomswitchboardform.Ifyou’reworriedaboutusersfiddlingwiththe

tables,forms,andreportsinyourdatabase,it’softenhelpfultohidetheDatabaseWindow.

SavvyuserscanstillaccesstheDatabaseWindow(unlessyoutakefurtherstepstosecurethe

database),buthidingtheDatabaseWindowthroughthestartupformatleastmakesitalittleless

temptingtofiddle.

4.

ClickOKtosaveyourchanges.

Thenexttimeyoulaunchyourdatabase,theMySwitchboardformwillautomaticallyloadforyour

users.Youcanhaveseveralswitchboardswithinyourapplication.Forexample,youmightwanttohave

amainswitchboardthatallowsyouruserstoexplorevariousaspectsoftheapplicationsuchasdata

entry,reporting,andapplicationoptions(suchastoolbarcustomizationsorsecurityoptions).Whenyour

usersselectthereportingbutton,youcanlaunchaseparatereportingswitchboardwithbuttonsforallof

thereportsinyourapplication.

(46)

Introduction

to

Microsoft

Access

Create

a

Switchboard

through

the

Switchboard

Manager

There’sanothereasywaytocreateaswitchboardforyourapplication.YoucanusetheSwitchboard

Managertocreateanewswitchboardoreditanexistingswitchboard.ChooseDatabase Utilities

fromtheToolsmenuandselectSwitchboard Managerfromthepopoutmenu(seeFigure1-11).

Figure1-11

Tocreateanewswitchboard,clicktheNewbutton.Enteranameforyournewswitchboard.Onceyou’ve

createdyourswitchboard,clickEdittocontroltheitemsdisplayedonyourswitchboard.Foranew

switchboard,therewon’tbeanyitemsontheswitchboard.NowclickNew(Figure1-12).Youcanenterthe

textdisplayedonyourswitchboardandchooseacommandfromthedrop-downmenu.Youcanchoose

fromeightdifferentcommandsincludingopeningaforminaddoreditmode,exitingtheapplication,

runningareport,orrunningcodeoramacro.Dependingonthecommandyouchoose,thethird

drop-downmenuwillchangeandallowyoutochooseaparticularform,report,ormacro.

Onceyou’veaddedallofthenecessarycommandstoyourswitchboardform,clickClosetoreturntothe

Switchboard Manager.Ifyouwantyournewswitchboardtolaunchwhenthedatabaseloads,selectit intheSwitchboard PagesboxandclickMake Default.Whenyou’redonemanipulatingyour

switchboards,clickClose.

Referensi

Dokumen terkait

Produk ini memiliki keunggulan yang tidak perlu diragukan kembali, yakni rengginang singkong merupakan produk yang aman untuk dikonsumsi, bermanfaat

[r]

Hal ini terjadi apabila FBIR meningkat, menunjukkan telah terjadi peningkatan pendapatan operasional diluar luar pendapatan bunga lebih besar dari pada peningkatan

Dengan adanya permasalahan dalam mencapai standard performansi, maka dalam penelitian ini digunakan metode Data Envelopment Analysis (DEA) yang merupakan metode pembanding yang

Memecahkan masalah merupakan tindakan siswa yang harus dihadapi dan menyelesaikan masalah yang sedang dihadapi. Karena guru memiliki banyak tugas dalam

Berdasarkan dari perhitungan hipotesa diatas dapat disimpulkan bahwa ada faktor-faktor yang berpengaruh terhadap respon rasa yaitu faktor gula, sari udang, tepung ketan,

Similarity from a chosen source Possible character

1) Untuk mengetahui dan menilai apakah pengendalian internal kas dilakukan secara memadai. 2) Untuk mengetahui apakah pengelolaan kas telah dilakukan secara efektif.