Before we look at the different variable declarations, we need to establish the difference between the words explicit and implicit. - explicit is defined as: "stated clearly and in detail, leaving no room for confusion or doubt."
- implicit is defined as: "implied, rather than expressly stated"
When coding in Visual Basic, you are by default not obligated to declare your variables before using them. This an example of an implicit variable declaration. When doing so, VBA will automatically declare it as a variant type provided that the variable has not been declared before. This is a nice feature, but may cause trouble when writing larger scripts. Let's look at an example: We have already written a lot of code using the variable "MyVariable". If we were to misspell "MyVariable" with "MyVaiable" once, VBA will think of it as a new variable, and declare it automatically, thus not informing us. Code Block |
---|
| MyVariable = 4
'We want to multiply MyVariable with 10
MyVaiable = MyVariable * 10
'... lots of code
'When we finally display MyVariable, thinking it equals 40
MsgBox MyVariable
'4 is displayed |
To avoid this problem, we can use the Option Explicit Statement. It ensures that all variables must be explicitly declared by using the Dim, Private, Public, ReDim or Static statements. Otherwise, it will display an error at compile time. If used, the "Option Explicit" statement must appear in a module before any procedures. Code Block |
---|
| Option Explicit
Sub Example()
'Explicitly declaring MyVariable as an integer
Dim MyVariable As Integer
MyVariable = 4
'We want to multiply MyVariable with 10
MyVaiable = MyVariable * 10
'... lots of code
'When we finally display MyVariable, thinking it equals 40
MsgBox MyVariable
'4 is displayed
End Sub |
Compiling the code above will result in the following error message. ![](/wiki/download/attachments/151453808/image2019-7-29_14-39-53.png?version=1&modificationDate=1564403993000&api=v2)
If you want to make all your modules have the "Option Explicit" statement, without having to remember to write it yourself, follow these instructions: - In your VBA editor, go
|