In this post, you’ll be learning how to use option explicit when working with your Excel Spreadsheet while you using Excel VBA.
How to use Option Explicit in Excel VBA?
Option Explicit is used to prevent the usage of variables that are not declared and misspelled. Declaring Option Explicit at the starting of your code module, commands VBA to require to declare all the variables which you are using in the code.
Using the Variables with Option Explicit
To use the variables with option Explicit,
Option Explicit Private Sub ExampleWithOptionExplicit() Dim strAlpha As String strAlpha = "Excel VBA with Option Explicit" MsgBox strAllpha End Sub
When we run the code, we get the error “Variable not defined”, because we didn’t declare the strAllpha variable.
So, when we correct the misspelled variable, the program runs successfully.
Adding Option Explicit at the top of your code modules helps prevent errors from misspelled variables.