Option Explicit

In a strongly typed language all your variables must be declared with a single data type.
In a loosely (or weak) typed language variables do not have to be declared before they can be used.
VBA is not a Strongly Typed programming language by default.
This means you can get away with not explicitly declaring the data type of your variables before you use them.

Sub Procedure() 
   MyVariable1 = 20
   MyVariable2 = MyVariable1 * 10

This is very bad practice and leads to code that is slow and difficult to read.
Explicitly declaring all your variables will make your code run faster and use less memory.
Including "Option Explicit" at the top of your code module will force you to explicitly declare the data type of each variable before it can be used.

Option Explicit 
Sub Procedure()
   Dim MyVariable1 As Integer
   Dim MyVariable2 As Integer

Check You Options

Select (Tools > Options)(Editor tab, Require Variable Declaration) and make sure it is checked.
Selecting this check box will automatically add the statement Option Explicit to any new modules (not existing ones).
This ensures that your code will not run if it contains any variables that have not been explicitly declared.
Changing this option will not affect any existing modules.

alt text

Compile-Time Error

Without Option Explicit any undeclared or misspelt variables will be automatically declared with the Variant data type.
When the Require Variable Declaration check box is ticked you will see the following compile-time error when it finds a variable that has not been declared.

alt text

Unpredictable Results

If you do not use Option Explicit it can lead to unpredictable results and run-time errors.
When you do not explicitly declare your variables anything that is not recognised as a keyword, statement or function is assumed to be a variable.
Therefore if you accidently mis-spell a variable a new one will be created causing you some odd results.


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext