Search notes:

VBA statement: dim

The dim statement allows to declare the data type of variables.
Don't confuse dim with declare.
The option explicit statement ensures that variables are declared with a dim statement. The dim statement is also necessary when defType or type-declaration characters are used.
In order to declare a global variable, the public statement is needed.

dim … as new …

The following special construct declare and initializes an object-variable in one statement:
dim obj as new someClass
However, the object is initialized only when it is first referenced, see beware of the dim … as new … statement.

Declaring multiple variables with one dim statement

It is possible to declare multiple variables with one dim statement like so:
dim v1, v2 as long
Unfortunately, this does not do what might be expected: the type of v1 will be a variant:
option explicit

sub main() ' {

    dim v1, v2 as long

    debug.print("typeName(v1) = " & typename(v1))
    debug.print("typeName(v2) = " & typename(v2))
    '
    '  typeName(v1) = Empty
    '  typeName(v2) = Long

    v1 = 42
    v2 = 99

    debug.print("typeName(v1) = " & typename(v1))
    debug.print("typeName(v2) = " & typename(v2))
    '
    '  typeName(v1) = Integer
    '  typeName(v2) = Long

    v1 = "v1 is a actually a variant"
 '  v2 = "v2 cannot be assigned a string"

    debug.print("typeName(v1) = " & typename(v1))
    debug.print("typeName(v2) = " & typename(v2))
    '
    '  typeName(v1) = String
    '  typeName(v2) = Long

end sub ' }
Github repository about-VBA, path: /language/statements/dim/beware.bas

A variable is declared for a sub/function, not for a scope

Unlike in C like languages, the dim statements belongs to the scope of the function within which it occurs, not within a narrower scope such as a looping statement.

See also

The const statement.
VBA statements

Index