Option Explicit is a VBA module setting that requires you to declare variables before using them. Put it at the top of each module, above its procedures, to catch misspelled or undeclared variable names before a macro runs; it does not declare variables for you or prevent every kind of programming error.
What Option Explicit means in Excel VBA
VBA normally allows an undeclared variable name to be used. If a name has not already been declared, VBA creates it implicitly as a Variant. That behavior can hide mistakes: a typo can become a separate variable rather than producing an immediate warning. Option Explicit changes that rule for the module where it appears. If code refers to a variable that has not been declared there or made available through a valid scope, VBA reports a compile error.
For example, if a procedure declares customerCount but later uses customersCount, the two spellings do not refer to the same variable. Without Option Explicit, the second name may be treated as a new, empty Variant. With the setting enabled, VBA identifies the undeclared name when the project is compiled or the procedure is run. Fixing that mistake early is usually easier than investigating a wrong result later.
The statement is written exactly as Option Explicit, with no value after it. It is a module-level directive, not a command that runs inside a procedure. It applies to the entire module, including its procedures, rather than to just the lines that follow it.
Where to put it and how to enable it
In Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor. On a Mac, Option+F11 usually opens it; depending on the keyboard, you may need Fn+Option+F11. In the editor, select the module you want to inspect in Project Explorer, then place the directive near the beginning of that module, before any Sub or Function procedure.
Option Explicit
Public Sub ExampleProcedure()
' Procedure code goes here.
End Sub
Comments can appear above the directive, but it must be outside procedures and before them. Add it separately to each standard module, worksheet module, workbook module, class module, or UserForm module where you want this checking. A directive in one module does not automatically govern the others.
To have the editor add the directive automatically to newly created modules, open the Visual Basic Editor and choose Tools > Options. On the Editor tab, select Require Variable Declaration. This preference affects new modules; it does not insert the statement into modules that already exist. Review older modules and add it to them if you want the same protection throughout the project.
After editing, use Debug > Compile VBAProject in the Visual Basic Editor to check for compile errors. The command may be unavailable when there is nothing to compile, or its wording may include the project name. Compilation checks code structure and declarations; it does not run the macro or verify that its results are logically correct.
Declaring variables after you turn it on
Once a module uses Option Explicit, declare every variable before its first use. The usual declarations are Dim for a procedure-level variable, Private for a module-level variable available within that module, and Public for a variable intended to be available more broadly in a VBA project. A variable’s scope determines where code can use it; declaration and scope are related, but they are not the same thing.
Include a data type when you know what kind of value the variable should hold. For example, Long is commonly used for row numbers, String for text, and Worksheet for an Excel worksheet object. If you write Dim item without an As clause, VBA still permits it, but the variable is a Variant. Option Explicit requires a declaration, not a specific data type.
- Use
Dim rowNumber As Longfor an integer-style row index. - Use
Dim customerName As Stringfor text. - Use
Dim reportSheet As Worksheetfor a worksheet reference. Assign an object withSet. - Use
Dim amount As Currencyfor many values representing money, while keeping the limits and rounding behavior of that type in mind.
VBA declarations can be placed at the beginning of a procedure or before the first use, though grouping them at the top often makes the procedure easier to review. Each variable needs its own type declaration if you want it typed: in Dim firstName, lastName As String, only lastName is a String; firstName is a Variant. Write Dim firstName As String, lastName As String when both should be strings.
A practical example with declared variables
This example totals numeric entries in column B of a worksheet named Sales, starting at row 2. It illustrates the directive, explicit data types, and object assignment. The example displays a total rather than changing worksheet cells.
Option Explicit
Public Sub ShowSalesTotal()
' Declare every variable used in this procedure.
Dim ws As Worksheet
Dim lastRow As Long
Dim rowNum As Long
Dim totalSales As Currency
Set ws = ThisWorkbook.Worksheets("Sales")
lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
For rowNum = 2 To lastRow
If IsNumeric(ws.Cells(rowNum, "B").Value) Then
totalSales = totalSales + CCur(ws.Cells(rowNum, "B").Value)
End If
Next rowNum
MsgBox "Total sales: " & Format(totalSales, "$#,##0.00")
End Sub
Here, ws refers to a worksheet, lastRow and rowNum hold row numbers, and totalSales holds the running total. ThisWorkbook means the workbook containing the VBA code. If the Sales sheet is missing, the macro will still encounter an error at the worksheet reference; Option Explicit does not check that a named sheet exists. The code also assumes the values in column B are suitable for conversion to Currency. Inspect and adapt it for your own workbook before use.
Save a copy of the workbook before running a macro. VBA actions generally cannot be reversed with Ctrl+Z, even if a particular example only displays a message. Save a macro-enabled workbook as an .xlsm file if you need to retain its VBA project. Excel for the web can open a workbook containing macros, but it cannot run, create, or edit VBA macros; use desktop Excel for those tasks.
Common compile errors and how to fix them
The most familiar error after adding the directive is “Variable not defined.” VBA highlights a name it cannot find as a declared variable. Check the spelling at both the declaration and the highlighted use, including singular and plural forms. Also check whether the declaration is in the same procedure or has a scope that makes it visible where it is used.
Other frequent causes include forgetting to declare a loop counter, a temporary value, or a variable used only in an error-handling branch. Copying code from a different procedure can also bring in variable names that were declared only in the original procedure. Declare the variable in the correct scope rather than removing Option Explicit simply to silence the error.
- If a new name is a typo, correct the use to match the intended variable.
- If it is a real, separate value, add a declaration with an appropriate type and scope.
- If the name should come from another module, check that it is exposed with a suitable scope and that the reference is valid.
- If compilation highlights a procedure or property rather than a variable, inspect the surrounding syntax and object references too; not every compile error is caused by Option Explicit.
VBA commonly adjusts the capitalization of a variable name in code to match its declaration. That can make inconsistent capitalization easier to spot, but capitalization alone does not create two different variable names. Spelling does matter: lastRow and lastRows are different names.
What Option Explicit catches—and what it does not
The directive is particularly useful for catching undeclared variable names, including many misspellings. It does not guarantee that a declared variable has the right type, contains the expected value, or is used correctly. A variable declared as a Variant remains a Variant, and VBA can still encounter type mismatches or unexpected values when the code runs.
It also does not prevent runtime errors such as referring to a worksheet that does not exist, dividing by zero, or trying to use an object that has not been assigned. Nor does it detect every typo in a late-bound object’s member name: when VBA cannot verify a member during compilation, the problem may appear only at runtime. Finally, the directive cannot identify a logically incorrect calculation that runs without an error. Testing with representative workbook data remains important.
Think of Option Explicit as an early spelling and declaration check, not a complete safety system or a substitute for testing. It improves the chance that a simple naming mistake is caught before execution, while leaving many design, data, and runtime concerns to the programmer.
Should you use it in every module?
For most maintained VBA projects, using Option Explicit consistently is a sound default. It makes variable use visible, helps catch accidental new names, and supports clearer code review. The main extra work is declaring variables and resolving errors that implicit Variants might otherwise conceal. That small discipline is usually worthwhile, especially in procedures that process many rows or update important workbook content.
Apply it module by module. Enabling Require Variable Declaration does not retrofit existing code, so a project can temporarily contain a mix of modules with and without the directive. When updating a legacy project, add it to one module at a time and compile, then resolve each undeclared name. Some highlighted names may reveal genuine typos; others may be legitimate variables that simply need explicit declarations.
Do not respond to a compile error by adding declarations indiscriminately. First decide what the name represents, where it should be available, and what type fits its use. A declaration such as Dim x may make the error disappear, but it leaves the variable as a Variant and may preserve the underlying confusion. Meaningful names and deliberate types make the benefit of Option Explicit stronger.
Frequently Asked Questions
Is Option Explicit required in Excel VBA?
No. VBA allows code without it, but undeclared names can become implicit Variant variables. Adding the directive is a widely useful way to make VBA require declarations in that module.
Where exactly does Option Explicit go?
Put it near the top of a module, outside all procedures and before any Sub or Function. It applies to the whole module, not just the code below its line.
Does Option Explicit declare variables automatically?
No. You must declare each variable yourself with a statement such as Dim rowNum As Long. The directive makes an undeclared variable a compile-time problem instead of silently creating it.
Why do I still get an error after declaring a variable?
The declaration may be misspelled, in a scope that is not available to the code using it, or attached to a different name. The error may also be unrelated to variable declarations. Read the highlighted name and compile again after correcting the cause.
Does Require Variable Declaration add Option Explicit to old modules?
No. In the Visual Basic Editor, Tools > Options > Editor > Require Variable Declaration adds the directive to newly created modules. Existing modules need to be updated separately.
Can I use VBA macros in Excel for the web?
You can open a workbook that contains VBA, but Excel for the web does not run or edit VBA macros. Open the file in desktop Excel to work with its VBA project.
Related
- How to Insert a Full-Width Horizontal Line in Word
- How to Insert a Fillable Checkbox in Microsoft Word
- Open a ZIP File in Excel: Extract and Import Data
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Lookup: Find Matching Data with CodeAn Excel VBA lookup searches a range for a value and returns related information, such as a product…
- VBA Macros in Google Sheets: What Works InsteadNo. Google Sheets cannot run VBA macros: VBA is Microsoft Excel’s programming language, and Sheets uses Google Apps…
- Excel VBA Range of Object Failed? Common Causes and FixesThe Excel VBA error “Method ‘Range’ of object ‘_Worksheet’ failed” usually means VBA could not resolve the address…
- Excel VBA Pivot Table Filter Multiple Values at OnceTo filter a standard Excel PivotTable to several items with VBA, clear the field’s existing filter and set…
- Excel VBA: Hide a Column by Number in Your WorksheetTo hide a column by its number in Excel VBA, set that worksheet column’s Hidden property to True.…
- Excel VBA Copy Paste Transpose: Working Code and TipsTo copy a range and paste it transposed with Excel VBA, copy the source range and use PasteSpecial…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.