VBA Option Explicit

Written by

Mel Jenkins

Reviewed by

Steve Rynearson

Last updated on March 20, 2024

Declaring Option Explicit at the top of your code module tells VBA to require that you declare all the variables which you are using in the code. If this command is omitted, you can use variables which you haven’t declared. We always recommend using the Option Explicit at the top of your module, as it helps you to avoid mistyping of the variables.

Using VBA Variables without Option Explicit

We will first show an example  when there is no Option Explicit command. Here is the code:

Private Sub ExampleWOOptionExplicit()
    strTextA = "Testing VBA without Option Explicit"
    MsgBox strTextA
End Sub

In the example, we declared the variable strTextA in the first row of the procedure and assigned it the text. After that, we want to return the message box with the value of strTextA. Here is the result when we run the code:

vba-without-option-explicit

 

As you can see in the above image, the code is successfully executed. The message box with the value from strTextA appeared, even though we didn’t declare variable strTextA.  Here there is no problem with the code, but what if we had misspelled the variable name:

MsgBox strTxtA

Here we wrote strTxtA (without an “e”) instead of strTextA. As a result we get a blank message box, because the variable strTxtA was not defined. Now we will see how to use Option Explicit to prevent errors.

Using the Variables with Option Explicit

If you want to prevent using variables that are not declared, you have to enter Option Explicit at the top of your module:

Option Explicit

Here is the complete code, including the typo:

Option Explicit
Private Sub ExampleWithOptionExplicit()

    Dim strTextA As String

    strTextA = "Testing VBA without Option Explicit"   

    MsgBox strTxtA

End Sub

Let’s see what happens if we run the code:

 

As a result, we get the error “Variable not defined”, because we didn’t declare the strTxtA variable.

Adding Option Explicit at the top of your code modules helps prevent errors from misspelled variables.

 

If you want to learn more about VBA other VBA options, learn about how to make VBA case-insensitive: Prevent VBA Case Sensitive

 

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as


Learn More!
vba-free-addin

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

Return to VBA Code Examples