‘ Only this Sub can see this variable.
Dim MyDimSubVariable As String
‘ Only this Sub can see this constant.
Const MySubConstant = “Hello”
End Sub
Begin by looking at the variables in Listing 4-1. The example includes three
declarations, along with their associated comments. Always include com-
ments with your declarations so that you know what purpose the variable
serves. The variable
declarations rely on
Public
and
Private
for scope
as well as on a data type keyword following the variable name to define the
data type. All the variables in this example are strings (or text), but VBA
supports many other data types. Using the
Dim
keyword makes a variable
private. However,
actually using the word
Private
is clearer, so that’s what
you should use in your code.
The next three declarations in Listing 4-1 are for constants. Notice that the first
constant declaration is for conditional compilation. This kind of declaration
always uses the
#Const
keyword. You can use this declaration in place of the
Conditional Compilation Arguments field entry (see the “Adding
conditional
compilation” section of Chapter 3 for details). You can’t define this type of con-
stant as private or public because VBA hides the value from other modules.
The other two kinds of constant declaration do rely on
Public
or
Private
for scope. Notice that you do include the keyword
Const
to mark the value
as a constant. The constant has a name and a value assigned to it. However,
notice that it doesn’t have a data type because you can’t
assign a data type
to a constant. VBA stores constants as a series of bits by using the type of
the information that you provide. Because you can never change the value
of a constant, the question of data type isn’t important. The fact that a con-
stant doesn’t have a data type is one reason that
it improves application per-
formance and is more efficient to store.
The next section of Listing 4-1 contains a
Sub
that includes both a constant
and a variable declaration. Variables or constants defined within a
Sub
or
Function
are private to that
Sub
or
Function
. Consequently,
VBA requires
that you use the
Dim
keyword in this case. Notice that the constant still
includes the
Const
keyword but lacks a
Private
or
Public
keyword for
the same reason.
Knowing which storage type to use
At first, it might seem like you should always use
variables so that you can
always access the data and change it. Variables do provide flexibility that
81
Do'stlaringiz bilan baham: