You do not have to declare a variable before using it. You can just include the statement
A variable will automatically be created for TempVal as a variant (default type), and it will have the value of 6.
However, a problem with doing this is that it can lead to subtle errors in your code if you misspell the name of the variable in a later statement. For example, if you refer to it as temval instead of tempval, you know what you mean but VBA does not. It assumes that temval is a new variable and assigns it as such. The old variable, tempval, is still there but is no longer being used. You now have two different variables, although you think you only have one. This can lead to enormous problems that can take some time to straighten out in your code.
To avoid the problem of misnaming variables, you can stipulate that VBA always generate an error message whenever it encounters a variable not declared. To do this, you'll need to go to the declarations section of the code module. If you look at a module within the VB Editor window, you will see a heading called (General) in the top left of the module window and a heading called (Declarations) in the top right of the module window. Click (Declarations), and you will go straight to the declarations section. Do not worry if it appears you are not typing into a defined section. Type the following statement. As soon as you type a declaration, a line will automatically appear underneath to show it is within the declarations section.
This prevents implicit declarations from being used. Now you have to define TempVal:
If you refer to temval during execution, an error message will be displayed, stating that the variable has not been defined.
NOTE: Option Explicit works on a per-module basis-it must be placed in the declarations section of every code module you want it to apply to unless you define the variable as a global variable. A global variable is valid right across your project and can be used by the code in any module. See the section later in this tutorial called "Global Variables."
Which method you use (implicit or explicit) depends on your personal preference. Coding is often much faster using implicit because you do not have to initially define your variables before you use them. You can simply make variable statements, and VBA will take care of the rest. However, as discussed, this can lead to errors unless you have a good memory for variables you are using and have the experience to know exactly what you are doing. Implicit can also make it more difficult for someone else to understand your code. Using Option Explicit is the best practice and helps stop runtime errors.