Subscriber only lesson.
Sign up to this course to view this lesson.
About this lesson
Why forgetting to set a simple flag can burn you in the long term.
Download this lesson’s exercise file.Explicit vs Implicit variables.xlsm
Explicit vs Implicit variables
The effect of Option Explicit
When to use
You should always use Option Explicit!
The importance of data types
If the data type is not set in your Dim statement, the data type defaults to Variant.
Effects of Variant types:
- The type is determined when code is run, not when it is created.
- When the routine is run, the type could change in different instances.
- Intellisense is not available as you code.
Forcing Variable Declaration
Failing to declare your variables while Option Explicit is NOT declared carries the following issues:
- Spelling mistakes create new variables on the fly.
- Data type for the variable may be inconsistent throughout the code.
- Errors not being discovered until runtime, instead of during design time.
To force variable declaration
- Go to Tools on the main toolbar, select Options, and in the Editor tab check the box for Require Variable Declaration.
- Type Object Explicit at the top of the code module.
Hints & tips
Declaring multiple variables on one line
- You may declare multiple variables with the same Dim statement
- eg. Dim var1 as Long, var2 as Double
- Make sure you declare the data type for each variable.
Lesson notes are only available for subscribers.