×

VBA Option Explicit

VBA Option Explicit

The Option Explicit in VBA is used to declare the variables at the top of your macro code. It is the most secure and easy option to maintain your variables. While coding, chances are there that the coder may forget to define a variable or mistakenly re-write the same variable or may misspell a variable.

The code may not display any error, but you will surely the user won’t get the desired output every time. Assume in a multi-national company where you have multiple lines of codes. If any variable is mistakenly forgotten or misspelled, it would become a cumbersome job to examine the thousand lines of code over and over again and rectify the code.

VBA has introduced a solution known as Option Explicit Statement to avoid these kinds of situations and mistakes. It is mandatory to declare this statement on the top of the VBA code, so as it can highlight all the variable which is not defined. 

Declaring Option Explicit statement allows you to declare all the variables in one place so as in the future if your code encounters an error, you can directly check at the top of your code module. You can also declare the global variables within the Option Explicit statement. If the Option Explicit statement is omitted, all undefined variables are declared with the Variant data type (the default type or Deftype statement). Thus, consuming more storage and effective the runtime. It is always recommendable to use the Option Explicit statement at the top of your module, as it prevents the mistyping of the variables and boosts the efficiency of your code.

Advantages of Option Explicit

  1. The Option Explicit statement is used to avoid the incorrect typing of exiting variables. For example: If you have declared the Option Explicit statement at the top of your module and you try to access an undefined variable, it would throw a runtime error.
  2. This command forces the explicit declaration of all your variables.
  3. This statement prevents the use of an undeclared variable that throws an error at compile time.
  4. If you have not declared the data type for your variable, the VBA compiler chooses the default underlying variant data type. Thus, it will consume time, and your macro will run slower. So, for such events, Option Explicit saves time.
  5. For the undefined variable, the compiler implicitly chooses the data type of your variable as a variant. In the list of data types, variant reserves the highest space of 16 bytes of data. Imagine every time you forget to mention the data type for your variable, and it will straightly consume 16 bytes memory. Thus, Option Explicit checks this issue as well and saves memory.

Example 1: Demonstrate an example of depicting the challenges faced without Option Explicit.

Step 1: Open the VBA developer tab either by using the shortcut keywords Alt +F11 or click on developer window -> visual basic editor.

Step 2: Visual Basic Editor will open. The next step is to create a module. Right-clicking on the VBA Project-> Click on Insert-> Click on Module.

VBA Option Explicit

Step 3: In the VBA Module window, write the following code

  • Introduce the subcategory following with your macro name
  • Declare your variable with Integer Data type
  • Initialize the variable with integer value 20
  • Write the logic to add 5 to the variable. Make sure that you deliberately type the wrong name for the variable.
  • Display the value of the variable with the help of a MsgBox

Code:

Sub OptionExplicit_Example1()
 'Defining the variable with Integer data type
 Dim iSum As Integer
 'initializing the variable with integer value 20
 iSum = 20
 'adding 5 with the variable’s value
 iSum = iSm + 5 'here variable ism is not declared
 'displaying the output of the variable after adding 5 to it 
 MsgBox ("The value for the variable is " & iSum)
 End Sub  
VBA Option Explicit

When you will run the above code, you will get the following output.

Output

VBA Option Explicit

Explanation:

You were expecting the output to be 25, but to your surprise, you get 5. This mismatch occurred because we have misspelled the variable in the code, and instead of ‘iSum’ we here mistakenly written ‘iSm’. Although it didn’t stop the program by displaying an error, it has definitely hampered the output’s quality. Now the programmer has to go back and look where the mistake has happened. Thus, it becomes quite a long and tedious task.

Example 2: Demonstrating the above example with Option Explicit.

Step 1: Open the VBA developer tab either by using the shortcut keywords Alt +F11 or click on developer window -> visual basic editor.

Step 2: Visual Basic Editor will open. The next step is to create a module. Right-clicking on the VBA Project-> Click on Insert-> Click on Module.

VBA Option Explicit

Step 3: In the VBA Module window, write the following code

  • Declare the Option Explicit statement at the top of your module
  • Introduce the subcategory following with your macro name
  • Declare your variable with Integer Data type
  • Initialize the variable with integer value 20
  • Write the logic to add 5 to the variable. Make sure that you deliberately type the wrong name for the variable.
  • Display the value of the variable with the help of a MsgBox

Code:

'Declaring the Option Explicit statement
 'at the beginning of the module
 Option Explicit
 Sub OptionExplicit_Example1()
 'Defining the variable with Integer data type
 Dim iSum As Integer
 'initializing the variable with integer value 20 
 iSum = 20
 'adding 5 with the variable’s value
 iSum = iSm + 5 'here variable ism is not declared
 'displaying the output of the variable after adding 5 to it
 MsgBox ("The value for the variable is " & iSum)
 End Sub 
VBA Option Explicit

Output

VBA Option Explicit

Explanation:

You will notice that the program will throw an error as you have used a variable that is not defined. It will automatically highlight the variable a well. Now, you can easily check whether it’s a typo error or variable is not defined.

Option Explicit Automatic Method

So far, we have learned regarding the Option Explicit option, its advantages, and how to implement it.  It is advisable to use this command every time before the start of your code. So, VBA launched another method by which we don’t have to write the statement over and again on every page of our code. We have to modify a few instructions, and the VBA will automatically insert the Option Explicit statement at the top of all our modules

Follow the below points to enables this method:

Step 1: Open the VBA Editor window and click on Tools tab from the headers of the VB Editor. The toolbox will appear from there select Options.

VBA Option Explicit

Step 2: The Options wizard box will pop up, as shown below.

VBA Option Explicit

Step 3: In the Editor’s window, tick on the “Require Variable Declaration” checkbox option. Click on Ok.

VBA Option Explicit

Create a module, or if you have an existing module, restart it. You will notice that every time you introduce a new module, the Option Explicit statement is implicitly implemented at the top of your code. In the below example, we have created another module named ‘Module 2’, and this command is automatically present at the top.

VBA Option Explicit

Related Topics

Userform Events

What are Events? Anything you do in to trigger an excel file is an event (an action). Example: If you want a greeting message ‘Good Day’ whenever an excel file is...

7 minutes read.

Excel VBA TimeValue Function

Excel VBA TimeValue Function: The TimeValue function in VBA returns a Time from the specified String interpretation of a time /date where the date information for the given string is...

1 minute read.

Excel VBA Len Function

VBA Len Function: The Len function in VBA returns the number of characters in a supplied string or the number of bytes required to store a supplied variable. Syntax Len (Expression) Parameter Expression (required)-...

1 minute read.

Steps to Create a Chart in VBA

Steps to Create a Chart Charts are created either by directly working with the chart variable object that defines the chart data or by ChartObject method. In order to get to...

3 minutes read.

Excel VBA MessageBox

Message Box The MsgBox in Excel VBA is a dialog box used to inform the users of your program by showing a custom message or get some necessary inputs such as Yes/No or...

4 minutes read.

Excel VBA While wend Loop

WHILE wend loop is used when the user is not sure how many times they want to execute the VBA code within the program. With a WHILE loop, the loop body may...

3 minutes read.

VBA Color Index Property

What is Color Index Property? The Excel VBA Color Index is used to change the color for the cell or range of cells or text (located under the Font section). It sets the color...

5 minutes read.

Excel VBA FormatNumber Function

VBA FormatNumber Function: The FormatNumber function in VBA is used to apply a number format to a numeric expression, and it returns the result as a string. Syntax FormatNumber (Expression, [NumDigitsAfterDecimal], [IncludeLeadingDigit], [UseParensForNegativeNumbers], [GroupDigits]) Parameter Expression (required)...

2 minutes read.

Excel VBA Filter Function

VBA Filter Function: The Filter function in VBA returns a subset for the given string array, based on specified criteria. Syntax Filter (SourceArray, Match, [Include], [Compare]) Parameter SourceArray (required) – This parameter the array of Strings that you...

2 minutes read.

Excel VBA: DO WHILE….Loop

DO WHILE….Loop The “Do While” Loop is the same, unlike the FOR statement, just that it will keep on looping till the specified condition is true. It is used when we want to...

3 minutes read.

Excel VBA Right Function

VBA Right Function: The Right function in VBA returns a substring from the end of the given string. Syntax Right (Str, Length) Parameter Str (required) – This parameter represents the string from which you want to...

1 minute read.

Excel VBA- Pivot Table Fields

VBA- Pivot Table Fields: The Pivot Fields collection contains all the fields from the data source, including any calculated fields. The main aspect of adding a field is its Position...

4 minutes read.

Procedures in VBA

Procedures in VBA A procedure is a block of statements or units of computer code that performs some action. It is enclosed with a declaration statement, and its primary purpose is to carry out...

3 minutes read.

VBA ListBox

What is a ListBox? ListBox refers to a permanently displayed control (usually box-shaped) which contains a list of objects (or attribute, or elements) from which the user can select single or multiple attributes....

8 minutes read.

Excel VBA Rnd Function

VBA Rnd Function: The Rnd function in VBA returns a random number that is greater than or equal to (>=) 0 and is less than (<) 1. Syntax Rnd ([Number]) Parameter Number (optional) –This...

1 minute read.

Excel VBA Error Handling

What is Errors and Types of Error? Errors are conditions that resist the flow of the program or enables a problem while running any programming. There are three types of errors in VBA...

5 minutes read.

Excel VBA LTrim Function

VBA LTrim Function: The LTrim function in VBA removes the leading spaces from a supplied text string. Syntax LTrim (String) Parameter String (required) - This parameter represents he text string that you want to remove...

1 minute read.

Excel VBA Left Function

VBA Left Function: The Left function in VBA returns a substring from the start of the specified string. Syntax Left (Str, Length) Parameter Str (required) – This parameter represents the string that you want to extract...

1 minute read.

Excel VBA Val Function

VBA Val Function: The Val function in VBA converts the given string into a numeric value. This function ignores spaces and continues to read the characters after space(s). It stops...

1 minute read.

Excel VBA: IF…..THEN …ELSE Statement

VBA : IF…..THEN …ELSE Statement: This function enables you to check one condition and, based on that, then run one of the two statement blocks present. If the ‘IF’ condition...

2 minutes read.