Where to DIM

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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?
 
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
 
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?

Unlike some other languages, all VBA variables in a procedure are "dimmed"
regardless of where you do so. That being the case I prefer to do all of that
at the top of the procedure so they are all in one place.
 
Back
Top