Declarations variables, Dim, some guidance please
By preference (and it's *mostly* preference), I try to declare only
procedure arguments and local (procedure-level) variables. This is
especially useful in large applications where one may not be sure that a
global/module-level variable isn't changed by an unrelated procedure.
You didn't get a duplicate Dim error because one variable was declared
at the module level, and one was declared within the sub. Local
variables always override global variables within their own procedure.
This is actually an advantage, as one can re-use variable names within
multiple procedures, but each procedure sees only its own, local
variable. For instance, note the reuse of "i" in:
Public Sub Sub1()
Dim i As Long
For i = 1 To 10
Sub2 "Iteration " & i & ": "
Next i
End Sub
Public Sub Sub2(ByVal sStr As String)
Dim i As Long
For i = 1 To 3
Debug.Print sStr & i
Next i
End Sub
If your code is fairly small, and will never be maintained by anyone
else, using module-level variables is probably fine, as long as you keep
track of which procedures are modifying them, and when.
If you're writing code that will be maintained by others, I'd strongly
recommend using local variables as much as possible.
In article ,
Neal Zimm wrote:
In an application that I'm developing I have dim'd quite a few variables in
Declarations. I'll admit some of it is not wanting to take the time to put
those vars that are used quite often in many macros within the sub
SubName(var list) parenthesis.
1) What advice can you offer on the pro's and cons of this technique? All of
the application's code is in ONE module.
2) I got 'bitten' when testing a macro where a var called Draw was dim'd as
integer in Declarations, had a good value 0 in prior macros, but was 0 in
the macro I was testing.
Sure enough, I had dim'd it again, inadvertantly, also as Integer in the
macro being tested. Hence the 0 value, I guess. The QUESTION is, why did I
NOT get a duplicate Dim error?
|