Learn Access 2003 VBA with The Smart Method
72
www.LearnAccessVBA.com
Lesson 4-1: Understand subs
Most real-world tasks can be broken down into smaller tasks. In
programming we call tasks procedures. Procedures can be split into Sub
procedures. Consider the procedure of opening your front door. It can be
broken down into several sub-procedures:
Insert key
Turn key anti-clockwise
Push door inwards
Remove key
Close door
Defining procedures in VBA code
In VBA we cannot leave spaces in procedure names so we would name
the above sub-procedures:
InsertKey, TurnKeyAntiClockwise, PushDoorInwards, RemoveKey and
CloseDoor.
In VBA code we use the keywords Sub and End Sub to de-lineate
procedures and sub-procedures. There’s no distinct difference between a
Sub-procedure and a Procedure as they are all de-lineated by the Sub…
End Sub statements.
Most VBA programmers refer to sub-procedures simply as Subs. The
InsertKey sub would thus be typed into the editor as follows:
Sub InsertKey()
‘ InsertKey VBA code will go here
End Sub
Note two more things about the above code. We have added parenthesis
after the Sub Procedure’s name and also a single quotation mark in front
of the comment InsertKey VBA code will go here. Comments in code are
ignored by VBA and can be used to add comments to describe what your
code does and how it works.
Calling procedures in VBA code
To execute all of the sub procedures we have discussed and open the
door we would call the subs in sequence like this:
Sub OpenDoor()
Call InsertKey
Call TurnKeyAntiClockwise
Call PushDoorInwards
Call RemoveKey
Call CloseDoor
End Sub
tip
Always use the Upper/Lower
Case naming convention for
Sub names (as used in
TurnKeyAntiClockwise)
Never use underscores in your
own sub names and then it will
always be clear which subs are
event handlers.
Never, ever, abbreviate words,
for example do not use sub
names such as
TrnKeyAntiClkwse.
These rules (and the reasons for
them) are listed in Appendix A:
The Rules.
note
Sometimes you’ll hear the term
Sub Routine used instead of
Sub Procedure. You’ll also hear
some people refer to Sub
Procedures as simply
Procedures.
None of this terminology is
incorrect; we just have many
different words that refer to
exactly the same thing.
We will simply use the word
Sub in this book.
Session4