You should declare every variable you use in your program, to tell the Visual Basic compiler the variable's data type and other information such as what code can access it. The following example declares a variable to hold an Integer value.
Dim numberOfStudents As Integer
You can use Dim only at module or procedure level. This means the declaration context for a variable must be a class, structure, module, procedure, or block, and cannot be a source file, namespace, or interface. For more information, see Declaration Contexts and Default Access Levels.
If Option Explicit is On (the default), the compiler requires a declaration for every variable you use. If you turn Option Explicit Off, every undeclared variable defaults to the Object Data Type, which might not be your intention.
You can specify each variable's data type in the Dim statement. You can also specify an initial value. If you do not, Visual Basic uses default settings. For more information, see "Data Type Rules" and "Default Values" under "Detailed Information" on this Help page. The following example declares and initializes a String variable.
Dim summary As String = "Summary of results"
You can specify what code can access a variable by supplying an accessmodifier in the Dim statement. For more information, see "Modifiers" and "Access Level" under "Detailed Information" on this Help page.
You can declare a variable to hold an array, which can hold multiple values. For more information, see "Array Rules" under "Detailed Information" on this Help page. For more information on arrays, see Arrays in Visual Basic. The following example declares an Integer array variable.
In general, you should put all your Dim statements at the beginning of the code region in which you use the variables. For more information, see "Troubleshooting" under "Detailed Information" on this Help page.