Option Explicit is a statement used in VBA programming and it always declares at the top of the code. When Option Explicit appears in a file, you must explicitly declare all variables by using the Dim or ReDim statements. If you try to use an undeclared variable name, an error occurs at compile time.
We strongly recommend to use Option Explicit at the start of your Excel VBA code. Using Option Explicit forces you to declare all your variables.
For example, place the following code lines in you VBA Editor and run the program:
Option Explicit
Sub Option_Explicit()
Dim myVar As Integer
myVar = 10
Range("A1").Value = mVar
End Sub
As a result you will get a "Compile error: Variable not defined" error message pop-up:
This error pops-up as, cell A1 does not contain the value 10. That is because we accidentally misspelled myVar. As a result, Excel VBA places the value of the undeclared, empty variable mVar into cell A1.
When using Option Explicit, the code lines above generate an error because we did not declare the variable mVar.
To fix such error, follow the following steps:
- Click OK on the error box (as shown in above screenshot) and Stop the debugging.
- Correct the variable name from mVar to myVar so that it reads what we have declared.
- Run the program or code again
Now, I hope you know why you should always use Option Explicit at the start of your Excel VBA code as it avoids incorrectly typing the name of an existing variable.
Fortunately, you can instruct Excel VBA to automatically add Option Explicit.
No comments:
Post a Comment