VBA Option Explicit

Associated Files Download Links

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 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 the example of the code when there is no Option Explicit command. Here is the code:

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

Image 1. The code without Option Explicit

 

As you can see in Image 1, 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:

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:

Here is the complete code, including the typo:

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

Image 2. The code with Option Explicit

 

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

 

You may also like some of this related content...

Advertisements
Automate Excel
Left Menu Icon