Everything About Option Explicit in VBA
As a developer, it is a good practice to declare your variables in a script/code so that you immediately get the source of an error when running it.
Option Explicit is used in VBA precisely to make the defining of variables mandatory while writing code. This statement is very important when you have a script with many lines of code; when there is a bug due to a wrong spelling of a variable for example, if the variables were not defined, it will be very cumbersome and tiring to identify the origin of the bug.
Because to do so, you have to check the code line after line over and over again. After reading this article, you are going to better understand the importance of the Option Explicit statement and how to use it.
How to write the Explicit Statement in VBA in a Module
There are two methods to use this function in VBA. The first one is manual, meaning that you have to write the Option Explicit at the beginning of each module. The second method is automatic and it is done through the settings of the VBA editor.
Method Number 1
Step 1: Select the developer tab on the Excel menu and click on the Visual Basic option or Click on Alt + F11 simultaneously.
Step 2: Select the Insert tab of the VBA Editor and click on the Module option
Step 3: Write the Option Explicit statement on the top of the module before writing any procedure.
This method is not recommended because you have to write the Option Explicit statement on every page of your code. It is not only tiring (Programmers hate repetition) and at times you might forget to write it. The second method that follows will solve the problem.
Method Number 2
With this method, the Option Explicit statement will automatically be inserted in all your modules. To achieve that, just follow the steps below:
Step 1: From the Menu Bar of the VB Editor click on Tools Tab, from the dropdown list of options click on Options as shown below.
Step 2: After clicking on Options the wizard box opens as shown below.
Step 3: Select the option for “Require Variable Declaration” and then press OK.
Create a new Module or restart an existing one in the VB Editor to see the changes. You can notice that Option Explicit statement will be automatically written in the Modules, thereby forcing the programmer to declare variables before using them.
Hope it was useful.