What is Option Explicit?
As you know declaring a variable before using it is a good practice. Option Explicit declaration forces users to declare or define a variable before using it.
Using Option Explicit is a good practice. It is declared at the very top before any code line. Option Explicit declaration helps in debugging a programme quickly.
In the above image you can see Option Explicit at the very top. If you run displayMsgBox sub then it will run as expected without any issue since msgStr variable is first declared before assigning value to it.
Now if you run above Sub then it will throw Variable Not Defined compile error. This is due to Option Explicit is used and msgStr variable not declared before using it.
In the above image Option Explicit is not present hence running above sub will display message without any error, even if the variable is not declared before getting used.
Now imagine if you have Sub with 100 or more code lines and you just somehow mis-spelled msgStr to msgSt in Msgbox like this Msgbox msgSt. In this case without Option Explicit programme will run and will give you message without any string display and you will wonder why this has happened. Now declare Option Explicit at very top and run, it will quickly throw error at Msgbox msgSt line saying Variable Not Defined.
Auto declaring Option Explicit in VBA
One can write Option Explicit manually or get it declared automatically.
To declare it automatically follow the below steps.
1- Click on Tools tab in VBA IDE.
2- Click on Options.
3- In Editor tab , tick on Require Variable Declaration then click on Ok.
Note:-This is one time setting only ,after this whenever you create new module or new project Option Explicit will be there automatically at the very top.