Where to DIM

D

Dave180

Is it good practice to DIM all variables at the top of a large module or
better to Dim a variable that may be required within a Sub / Function, or
indeed within a conditional clause, within that module so that it is only
DIMed when it is guaranteed to be required?
 
S

Stuart McCall

Dave180 said:
Is it good practice to DIM all variables at the top of a large module or
better to Dim a variable that may be required within a Sub / Function, or
indeed within a conditional clause, within that module so that it is only
DIMed when it is guaranteed to be required?

In general you should keep the scope of the variable as tight as possible.
So if the var is only used in one procedure, declare (Dim) at the top of
that procedure's code.

If the var is used by more than one procedure, declare it at the module
level ie before any procedure code.
Another way to achieve the same effect is to declare the var as a parameter
to each procedure that will make use of it, then pass it from procedure to
procedure

Sub Proc1()
Dim variable as <whatever>
Call Proc2(variable)
End Sub

Sub Proc2(v As <whatever>)
MsgBox v
End Sub
 
Top