Option Explicit: Excel Easy
Option Explicit: Excel Easy
Excel Easy
#1 Excel tutorial on the net Excel Introduction Basics Functions Data Analysis VBA 300 Examples Ask us
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. Chapter < >
For example, place a command button on your worksheet and add the following code lines: Variables
Dim myVar As Integer
myVar = 10
Range("A1").Value = mVar Learn more, it's easy
Result when you click the command button on the sheet: Option Explicit
Variable Scope
Life of Variables
Clearly, 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.
Result:
https://www.excel-easy.com/vba/examples/option-explicit.html 1/3
02/10/2019 Excel VBA Option Explicit - Easy Excel Macros
Now you know why you should always use Option Explicit at the start of your Excel VBA code. It avoids
incorrectly typing the name of an existing variable.
Fortunately, you can instruct Excel VBA to automatically add Option Explicit.
1. In the Visual Basic Editor, click on Tools and then click on Options.
Note: Option Explicit will not be added automatically to existing Excel files. Simply type in Option Explicit yourself
if you want to use it.
https://www.excel-easy.com/vba/examples/option-explicit.html 2/3
02/10/2019 Excel VBA Option Explicit - Easy Excel Macros
OPTION EXPLICIT • FREE EXCEL HELP • COPYRIGHT (C) 2010-2019 • ALL RIGHTS RESERVED
MICROSOFT EXCEL TUTORIAL | HOW TO USE VBA & MACROS | EXCEL FORMULAS | FUNCTIONS IN EXCEL
https://www.excel-easy.com/vba/examples/option-explicit.html 3/3