Learn Access 2003 VBA with The Smart Method
92
www.LearnAccessVBA.com
Lesson 5-2: Understand and
implement strong typing and
explicit variable declaration
Weakly typed variables (that will always be of data type Variant) will
often result in problems such as “penny rounding" errors in financial
calculations. They also introduce the possibility of many potential bugs
remaining undetected in your code. For this reason they are never, ever,
used by professional programmers.
In the few cases where variants are useful a professional programmer
would still strongly type the variable as type Variant.
We’re going to strongly type the variables created earlier to tell VBA that
their data type is string.
We’re also going to improve our code yet further by switching on VBA’s
explicit variable declaration option in order to force all future variables to be
declared.
1
Open the VBACode.mdb database (if not already open) and
open frmTest in Design View.
2
Open the VBA Editor.
3
Edit the code in the ThankYouMessage sub.
In order to demonstrate the benefits of explicit variable declaration
we’ll introduce a bug. Change the line:
Call MsgBox(strMessage)
To:
Call MsgBox(strMassage)
Note the misspelling of strMassage in the second case.
4
Execute the buggy code.
Return to Form view and click the cmdPressMe command button.
An empty message box is displayed.
This happens because VBA created a new variable called
strMassage when it was encountered for the first time. Because
this new variable contained no text an empty message box was
displayed.
Consider the problems this could cause if you misspelt
dblProfitMargin as dblProfitMorgin and then used this value to
sell all of your goods at cost price!
It would be a better thing for this type of spelling mistake bug to
be trapped as soon as it occurs. We can do this with explicit
variable declaration.
5
Switch on explicit variable declaration.
Select Tools Options from the main menu and then click the
Editor tab. Check the Require Variable Declaration check box.
Session5