7/29/2019 vb_intr
1/14
Mi ch ae l Br yd on (m j br yd on @sfu. ca )Last updat e: 02-May-01 1 o f 14
Lesson 18: An introduction to VISUAL BASIC
18.1 Introduction: Learning the basics of
programming
Program mi ng can be enorm ously com plex anddif f i cul t , or i t can be easy and st ra ight forw ard.In many cases, t he dif f erence l i es in t he choiceof t ools used for w ri t ing the program. In othercases, it is a quest ion of scalelarge pr oj ect sare unavoidably complex.
In this proj ect , w e are going to f ocus on solvingsmall problems using an easy-to-useprogramm ing language. I t i s im port ant t orecognize, however, that basic programmingconcept s rem ain t he same r egardl ess oflanguage or pr oj ect scale. The pr ograms youcreate here are t r iv ial , but t hey int roduce a
handful of pr ogramm ing const ruct s t hat can bef ound in any t h ird generat ion language, not
j ust VISUAL BASIC.
Strict ly speaking, the language that isinc luded wi t h ACCESS is not VISUAL BASICi tis a subset of t he ful l, st and-alone VISUALBASIC language (whi ch MICROSOFT sellsseparately). In ACCESS version 2.0, t hesubset is called ACCESS BASIC . In version7.0 and above, it is sl i ghtl y enlargedsubset cal led VISUAL BASICFOR
APPLICATIONS (VBA). In t he context o f t hesimpl e programs we are wr i t ing here,
these terms are interchangeable.
ACCESS provides t wo w ays of int eract i ng wi t h theVBA language. The most useful of t he t w o issaved modules that contain VBA procedures.Procedur es are bat ches of programm ingcommands t hat can be executed t o do
int erest ing t hings l i ke process t ransact ionsagainst master tables, provide sophist icatederr or checking, and so on.
The second w ay to int eract wi t h VBA is d irect lyt hrough the int erpret er. When you type ast a tement in to t he in terpre t er, i t is executedimm ediately. Al t hough t here is l i t t le businessuse for t h is feat ure, i t does making learning thelanguage and t est ing new st at ement s easier.
In the f ir st part of t his lesson, you are going toinvoke ACCESS VBA interpret er and executesome very simpl e st at em ent s. In t he secondpart of t he tut or ia l , you are going to create VBA
modules t o explore generic programm ingconst ruct s such as looping, condit ionalbranching, and paramet er p assing.
!
http://map.pdf/7/29/2019 vb_intr
2/14
Learning object ives2 o f 14
An in t r oduct ion t o VISUAL BASIC
18.2 Learning objectives
! invoke and use the debug/ imm ediatewindow
! underst and t he di f f erence bet weenfundament al program const ruct s(st at ement s, vari ables, t he assignmentoperator, and predef ined funct ions)
! underst and t he di f f erence bet weensubroutines and functions
!creat e a modul e cont aining VBA code
! gain experience w it h looping andcondit ional branching const ruct s
! use t he VBA debugger i n ACCESS
! underst and t he di f f erence bet ween anin terpre t ed and compi led programming
language
18.3 Exercises
18.3.1 Invoking the interpreter
Click on the Modules t ab in t he databasewi ndow and press New.
This opens t he module window w hich we w i l lre tu rn to in Sect ion 18.3.3.
You have to have a modul e w indow openin order for t he debug window to be
avai lable f r om t he menu.
Select View Debug Window f r om themain menu. Note t hat Ctrl-G can be used inversion 7.0 and above as a short cut t o brin gup t he debug wi ndow.
In version 2.0 , t he debug window iscal led the imm ediat e window and youuse View Immediate Window t oact ivat e i t .
18.3.2 Basic programming constructsIn this section, you wil l use the VBA interpretert o explore some fundament al programm ingconst ruct s and VISUAL BASIC syntax.
18.3.2.1 Statements
St at ement s are built around special keyw ords ina programming language that do somethingwhen execut ed. For example, t he Printst atem ent in VBA print s an expression on t hescreen.
In the debug wi ndow, t ype the f o l lowi ng:
NL Print Hello world!
Th e symbol at t he end of a l i ne means press t he Return or Enter key . Fromt his point f orward, assume t hat each l ineis fo l l owed by an Enter.?
2
?
http://map.pdf/7/29/2019 vb_intr
3/14
Exercises3 o f 14
An in t r oduct ion t o VISUAL BASIC
In VBA (as in al l d ial ect s of BASIC), t he questi onmark (?) is t ypicall y used as short hand for t hePrint sta tement .
Type the f o l lowi ng int o the debug wi ndow:NL ? Hello world!
As show n in Figure 18.1, t he result is ident icalt o f i rst Print sta tement .
18.3.2.2 Action statements
Actions are special statements that allowprogrammers to use elements of ACCESS macro
language in VBA program s. Som e act ions arestand-alone (such as the MsgBox act ion below)and ot hers are actual ly m et hods of t he DoCmdobj ect (see Sect ion 18.4.1 for more in format ionon t he evolut ion of VBA and i t s incr easing use ofobj ect-or i ented concept s). Al t hough theinclusion of so many di f ferent t ypes of
st atem ent s result s in a conceptual m ess, i tprovides programers with a great deal off lexib i l i ty.
At this point, you should ignoretheoretical language issues and acceptVBA as a pow erf ul-but -inconsist ent
f r iend.
Type the f o l lowi ng int o the debug wi ndow:NL MsgBox Hello, world!
The MsgBox macr o act ion pr ovides an easy w ayt o cre ate cust om messages using t he st andard
WINDOWS m essage box f orm at .
The DoCmd obj ect i s j ust a kludge t hat br i ngsVBA, obj ect- or ientat ion, and t he macrolanguage t oget her. Ugly as it is, t he DoCmdobj ect has many met hods t hat are wort hlearning about .
FIGURE 18. 1: Int eract ing wit h t he VISUAL
BASIC in terpreter .
The debug window in version 8.0is shared with the locals window.?
Type VISUAL BASICstatements into theinterpreter.
1111
The statements executeimmediately and results areshown in the debug window.
2222
?
http://map.pdf/7/29/2019 vb_intr
4/14
Exercises4 o f 14
An in t r oduct ion t o VISUAL BASIC
Type the f o l lowi ng int o the debug wi ndow:NL DoCmd.OpenForm frmOrders
You wi l l not ice t hat your order f orm opens in
the background behind the debug window.
I f you do not have a form cal ledfrmOrders, t h is met hod wi l l r esu l t in anerror.
18.3.2.3 Variables and assignment
A variable i s space in mem ory t o which youassign a name and a value. When you use t hevariable name in expressions, the programminglanguage replaces t he variable name w it h i t sassigned value at t hat part i cular inst ant.
Type t he f o l low ing:
NL s = Hello
NL ? s & world
NL ? s & world
In t he f i rst st atem ent, t he variable named s iscreated and the st r ing Hel lo is assigned t o i t .Recal l t he funct ion of t he concatenat ionoperator f rom Sect ion 11.4.1. When the secondst at ement is execut ed, VBA recognizes t hat s isa variable, not a st r ing (since i t is not i nquotat ions marks). The int erpret er replaces swi t h i ts va lue ( Hel lo ) before execut ing t hePrint comm and. In t he f ina l st a tement , s is in
quotat ion marks so i t is int erpret ed as a literalstring.
Contrary to the practice in languages l ikeC and PASCAL, t he equals sign (=) is used t oassign values to variables. It is also usedas t he equivalence operator (e. g., does x= y?).
With in t he debug window, any st r ing of
characters in quotations marks (e.g., Hel lo ) is int erpre ted as a l i t e ral st r ing.Any st r ing wit hout quot at ion m arks (e.g. ,strName) is int erpr et ed as a vari able orsome ot her obj ect s (such as a f iel d) t hatis def ined wi t h in the ACCESS environment.
18.3.2.4 Predefined functionsYou were i ntr oduced t o predef i ned funct ions inSect ion 11.4.2. In t his sect ion, y ou are going t oexplore some basic predefined functions forworki ng wi t h numbers and text . The result s ofthese exercises are shown in Figure 18 .2.
Pri nt t he cosine of 2 radians and then nestt he cosine f unct ion w it h in a conversionfunct ion to round to t he nearest int eger:
NL pi = 3.14159
NL ? cos(2*pi)
NL ? CInt(cos(2*pi))
!
?
!
http://query2.pdf/http://query2.pdf/http://query2.pdf/http://query2.pdf/http://map.pdf/7/29/2019 vb_intr
5/14
Exercises5 o f 14
An in t r oduct ion t o VISUAL BASIC
Convert a st ring of charact ers t o uppercase:NL s = basic or cobol
NL ? UCase(s)
Ext ract t he middle six charact ers f r om ast r ing st ar t ing at t he f i f t h charact er :
NL ? mid (s,5,6)
Calculate t he monthly payment f or a$12,000 loan over f our years w it h 8.5%
int erest (nom inal) compounded mont hly:NL ? Pmt(0.085/12, 4*12, -12000)
In VBA, as in ACCESS, case is ignored. Assuch MID(S,5,6) is ident ical to
mid(s,5,6). In addi t ion, t he amount o f whi t espace (space betw een elements
of t he st a tement) is i r re levant .
18.3.2.5 Remark statements
When creati ng large programs, it is consider edgood programm ing pract ice t o include adequateint ernal documentat ion. In ot her words, youshould include comments throughout your codet o explain t o others and your fut ure self whatt he program is doing.
Comm ent l ines are ignored by the int erpret erw hen t he program i s run. To designate acomm ent in VBA, use an apost rophe t o st art t hecomment , e .g . :
NL This is a comment line!
NL Print Hello the comment starts
here
The original REM (remark) statement fromBASIC can also be used, but is less common.
NL REM This is also a comment (remark)
?
FIGURE 18. 2: Using t he V ISUAL BASICin terpr eter t o test pr edef ined funct ions.
The argument forcos() contains anexpression.
UCase() converts astring to uppercase.
Mid() extracts
characters from astring.
The debug window can beenlarged by dragging thedividing line.
?
Many specialized financial andscientific functions are available.
http://map.pdf/7/29/2019 vb_intr
6/14
Exercises6 o f 14
An in t r oduct ion t o VISUAL BASIC
18.3.3 Creating a module
So far, you have w ri t t en and execut ed VBAst atem ents one at a t ime. A more useful
t echnique is t o bundle a number of VBAcommands t oget her in a procedure and runthem in sequence. A module is a collection ofst atem ents that is saved w it h t he database ( l ikea form or a query).
Close the debug window so that the
declarat ion page of t he new m odulecreated in Sect ion 18.3.3 is visib le (seeFigure 18.3).
The tw o l ines:NL Option Compare Database
NL Option Explicit
are included in t he module by default . TheOption Compare st atem ent specif i es t he way inwhich st r ings are compared (e.g. , are wi rew hisk and WIRE WHISK consider edidentical?). The Option Explicit statementforces you to declare all your variables beforeusing t hem (variabl e declar at ion i s discussed inSect ion 18.3.4 .1) .
In version 2.0, ACCESS does not
aut omat ical ly add t heOption Explicit
statement. You should add it yourself tothe declarations section.
A module cont ains a declarat ion page and oneor more pages containing procedures. In VBA,t here are tw o t ypes of pr ocedures: subrout ines
and funct ions. The primary di f f erence bet weent he t wo is that subrout i nes simpl y executewhereas funct ions execut e and ret urn a value(e.g. , cos()) .
In version 2.0, only one subrout ine orfunct ion shows in t he window at a t im e.
You m ust use t he Page Up an d Page Downkeys to navigate the module.
FIGURE 18.3: The de clarat ions page of aVISUAL BASIC module.
2
2
http://map.pdf/7/29/2019 vb_intr
7/14
Exercises7 o f 14
An in t r oduct ion t o VISUAL BASIC
18.3.4 Creating subroutines with looping and
branching
In th is sect i on, you wi l l explore t wo of t he most
powerf ul const ruct s in comput er programming:looping and conditional branching.
Create a new subrout ine by t yping t hefol l owing anywhere on the declarat ionspage of t he open module:
NL Sub LoopingTest()
Not ice t hat ACCESS creates a new sect i on/ pagein t he module f or t he subrout ine, as shown inFigure 18.4.
18.3.4.1 Declaring variables
When you declare a variable, you te l l t heprogramm ing environm ent t o reserve some
space in memory for t he variable. Since t heamount of space t hat i s requi red depends ont he type of data t he variable is expected t ocontain (e. g. , st r ing, i nt eger, Boolean, double-precision f loat i ng-point , etc. ) , you have toinc lude data t ype in format ion in t he declara t ionsta tement .
In VBA, you use t he Dim st a tement t o declarevariables.
Type t he fo l l owing into t he space betw eent he Sub End Sub pair:
NL Sub LoopingTest()
NL Dim i as integerNL Dim s as string
NL End Sub
Save t he m odule as basTesting.
One of t he most usef ul loopi ng const ruct s isFor Next. A l l st a tementsbetw een t he For an d Next part s are repeatedas long as the part is t rue. Theindex i is automat ical ly increment ed af t er eachi tera t ion.
Enter t he remainder o f t he LoopingTestprogram:
FIGURE 18.4: Creat e a new subrout ine.
You can use the procedurecombo box to switch betweenprocedures in a module.
?
http://map.pdf/7/29/2019 vb_intr
8/14
Exercises8 o f 14
An in t r oduct ion t o VISUAL BASIC
NL Sub LoopingTest()
NL Dim i as integer
NL Dim s as string
NL s = Loop number:
NL F o r i = 1 T o 1 0
NL Debug.Print s & i
NL Next i
NL End Sub
Save t he m odule.
I t i s cust omary in m ost programm inglanguages t o use t he Tab key to indentt he element s wi t h in a loop sl ight l y. Thismakes t he program more readable.
Note that t he Print st a tement in Figure 18 .5 is
pref aced by Debug. You can get away w it h t heol d st yl e BASIC Print st a tement in t he debugwindow. But within modules, VBA enforces aform of ob j ect -or ienta t ion. A l l st and-a lonest atem ents are repl aced by m et hods of obj ects.In th is case, t he Print met hod window belongsto the Debug ob jec t .
18.3.4.2 Running the subroutine
Now t hat you have created a subrout ine, youneed to r un i t t o see t hat i t works. To invoke asubrout ine, you sim ply use it s name l ike youwould any statement.
Select View Debug Window f r om themenu (or p ress Ctrl-G in ver sion 7.0 andabove).
Type: LoopingTest in t he debug wi ndow, asshown in Figure 18.5.
18.3.4.3 Conditional branching
We can use a diff erent looping const ruct , DoUntil Loop, and the
condit ional branching const ruct ,
?
FIGURE 18.5: Run t he LoopingTestsubrout ine in t he debug wi ndow.
Invoke theLoopingTestsubroutine by typing itsname in the debug window.
1111
http://map.pdf/7/29/2019 vb_intr
9/14
Exercises9 o f 14
An in t r oduct ion t o VISUAL BASIC
If Then Else, to ach ieve thesame r esult .
Type the f o l lowi ng anywhere under t he EndSub st atem ent in order t o creat e a newpage in t he module:
NL Sub BranchingTest
Ent er t he fo l low ing program:NL Sub BranchingTest
NL Dim i As Integer, s As String
NL Dim blDone As Boolean
NL s = Loop number:
NL i = 1 initialize counter
NL blDone = False
NL Do Until blDone
NL If i > 10 Then
NLDebug.Print All done
NL blDone = True
NL Else
NL Debug.Print s & i
NL i = i + 1
NL End If
NL Loop
NL End Sub
Run t he pr ogram
18.3.5 Using the debugger
ACCESS provi des a very good debugger t o help
you st ep t hrough your programs and underst and
how t hey are execut ing. The t wo basicdebugging const ruct s explor ed here arebreakpoints an d stepping ( l ine-by-l ineexecut ion).
Move to t he Do Until blDone l ine in theBranchingTest subrout ine and selectRun Toggle Breakpoint f r om the menu(you can al so pr ess F9 t o toggle t hebreakpoint on a part icular l ine of code).
Not e t hat t he l ine becomes highl ighted,indicat ing t he presence of an act ive breakpoint .When the program runs, t he in terpre t er wi l lsuspend execut ion at t his breakpoint and passcontrol of t he program back to you.
Run t he subrout i ne f r om t he debug window.
Execut ion should halt at t he breakpoint .
St ep t hrough a couple of l ines in t heprogram line-by-l ine by pressing F8, asshown in Figure 18.6.
By st epping th rough a program l ine by l in e, you
can usually f ind any program bugs. In addit ion,you can use t he debug wi ndow t o examine t hevalue of variables whi l e t he program sexecution is suspended.
Click on t he debug wi ndow and t ype ? i t osee the curr ent value of t he variable i, as
shown in Figure 18.7.
E iA i d i V B
http://map.pdf/7/29/2019 vb_intr
10/14
Exercises10 o f 14
An in t r oduct ion t o VISUAL BASIC
18.3.6 Passing parameters
In t he BranchingTest subrout i ne, t he loopst art s at 1 and repeats unt i l t he counter ireaches 10. I t m ay be preferable, however, t oset t he st art and f in ish quant i t ies when t hesubrout ine is executed. To achieve thi s, you
pass parameters (or arguments) to thesubroutine.
The main difference between passed
parameters and other variables in a procedureis t hat p assed paramet ers are declar ed in t hef ir st l ine of the subrout ine def i n i t ion. Forexample, f o l lowi ng subrout ine declarat i on
NL Sub BranchingTest(intStart as
Integer, intStop as Integer)
not only declares t he variables intStart andintStop as int egers, i t also tel ls t he subrout ine
FIGURE 18.6: St ep t hrough t he each li ne int he program indiv idual l y.
The highlighted boxindicates the currentlocation of the interpreter inthe program. Press F8 toexecute one line of code.
2222
Use the F9 key to set abreakpoint where you want theprogram to suspend execution.
1111
FIGURE 18.7: Use t he debug w indow t opr in t var iab le va lues whi le t he program i s
running.
While the program executionis suspended, you canexecute statements in thedebug window. Type ? i toprint the current value of i.
1111
In version 8.0, the Localswindow shows the values of allvariables in the current scope.
?
E iA i t d t i t VISUAL BASIC
http://map.pdf/http://map.pdf/7/29/2019 vb_intr
11/14
Exercises11 o f 14
An in t r oduct ion t o VISUAL BASIC
t o expect t hese t w o number s t o be passed asparameters.
To see how t his w orks, cr eat e a new subrout ine
cal led ParameterTest based onBranchingTest.
Type the declarat ion st atem ent above tocreate t he ParameterTest subroutine.
Swi t ch back to BranchingTest and
highl ight a l l t he code except t he Sub andEnd Sub sta tements
Cut and past e t he code into t heParameterTest procedure.
To incorporate t he parameters into
ParameterTest, you wi l l have to m ake t hefol l owing modif i cat ions t o the past ed code:
Replace i = 1 w i t h i = intStart.
Replace i > 1 0 w i t h i > intStop.
Call t he subrout ine f r om t he debug wi ndowby t yping:
NL ParameterTest 4, 12
The result s are shown in Figure 18.8.
If you prefer enclosing parameters inbracket s, you have to use t he
Call (parameter1, ,
parametern) syntax, e.g. :Call ParameterTest(4, 12). SeeSect ion 18.4.3 for m ore in format ion ont he use of br acket s in VISUAL BASIC.
?
FIGURE 18.8: Creat e a param et eri zedsubroutine.
Include the names ofthe parameters in thesubroutinesdeclaration.
1111
DiscussionAn int r oduct ion t o VISUAL BASIC
http://map.pdf/http://map.pdf/7/29/2019 vb_intr
12/14
Discussion12 o f 14
An in t r oduct ion t o VISUAL BASIC
18.3.7 Creating a MinValue() function
In thi s sect ion, you are going t o creat e a user-def ined funct ion that r e turns t he min imum of
t wo number s. Alt hough m ost languages supplysuch a funct ion, ACCESS does not ( t he Min() and
Max() funct ion in ACCESS are f or use w it hin SQLst atem ents only).
Create a new m odule cal led basUtilities.
Type the f o l lowi ng (on one l ine) t o create anew funct ion:
NL Function MinValue(n1 as Single, n2
as Single) as Single
The st atem ent above def ines a funct ion cal ledMinValue that returns a single-precision
number. The funct ion requir es t wo single-preci sion num bers as paramet ers.
Since a funct ion ret urns a value, t he data t ypeof t he ret urn value should be specif ied in t hefunct ion declarat i on. Accordingly, t he basicsyntax of a funct ion declarat ion i s:
NL Function (parameter1As , , parametern As
) A s
The funct ion ret urns a variable named.
Type t he fo l l owing as t he body of t he
funct ion:
NL Function MinValue(n1 as Single, n2
as Single) as Single
NL If n1
7/29/2019 vb_intr
13/14
Discussion13 o f 14
An in t r oduct ion t o VISUAL BASIC
example, recal l t he Debug.Print met hod inSect ion 18.3.4.
18.4.2 Interpreted and compiled languages
VBA is an interpreted language. In int erpre tedlanguages, each l i ne of t he program is
int erpret ed (convert ed int o machine language)
and executed w hen the pr ogram is run. Ot herlan guages (such as C, PASCAL, FORTRAN, etc.)ar e compiled, m eaning t hat t he or ig inal(source) pr ogram is t ranslat ed and saved int o afi le of machine language commands. Theresult ing executable f i le is run inst ead of t hesource code.
FIGURE 18. 9: Test ing t he MinValue() funct ion.
Implement the MinValue()function using conditional branching.1111
These five lines could be replaced with animmediate if function: MinValue =iif(n1
7/29/2019 vb_intr
14/14
Appl ication to t he proj ect14 o f 14
An in t r oduct ion t o VISUAL BASIC
Predi ct ably, compi led l anguages run m uchfast er t han inter pret ed languages (e.g. ,compiled C++ is generally ten t imes faster thanin terpre ted JAVA) . However, interpreted
languages are generally easier to debug sinceprogram execution can be stopped at any pointand the curr ent l ine of source code viewed andmanipulated.
18.4.3 Brackets and parameters
Recall t hat subrout ines in VISUAL BASIC execut e abatch of commands, whereas funct ions execut ea batch of comm ands and ret urn a single value.The dist inct ion is im port ant because, when i tcomes to p assing paramet ers to procedur es,VISUAL BASIC adopt s an odd convent ion:
I f the procedure re turns a va lue ( i .e . , i t is afunct ion), enclose t he parameters inbrackets, e. g. , MinValue(2, 7).
I f the procedure does not re turn a va lue(i . e. , i t is a subrout ine), do not enclose theparamet ers in brackets, e.g. :ParameterTest 4, 12.
18.5 Application to the project
You w il l need a MinValue() funct ion inSect ion 19.5 when you have to det ermi ne thedefault quantity to ship. Ensure you have
created and t est ed the funct ion inSect ion 18.3.7.
http://event.pdf/http://event.pdf/http://map.pdf/Recommended