Should all variables be declared at the top of a sub?
Or is is better to declare them wherever they are
needed? I was doing the latter but I want to clean up my
code, problem is I don't know what "clean" is.
Printable View
Should all variables be declared at the top of a sub?
Or is is better to declare them wherever they are
needed? I was doing the latter but I want to clean up my
code, problem is I don't know what "clean" is.
It generally looks better if all the variables are declared at the beginning.
But, it's mainly your choice. :rolleyes:
IT depends on what scope you need, and sometimes you don't even need them!
All modulescope and public variables should be declared at top of each file. That doesn't mean you put types, constants enumerations and declarations in second, just that they are in the declarations sections means that they are in the top of the file, which ends where the first method starts.
Procedure scope variables should be declared at top ofin their procedures. parameters passed to them are automatically on top but next to that line you put the rest.
But some of these don't need to be used, depending on a selectional execution. IF's, select cases and exit subs can cause that. Then you declare the variable inside that if or behind that exit sub, but remember not to use it after the if statement.
Sometimes you have to declare variables within a subroutine or a function. A regular example of this is Recursion.
Actually that means you launch the a subroutine or function from within itself, causing procedure variables to be in several instances. Now if you use a Static variable, you can keep it the same even if you do recursive methods.
At Module and Global level, declare them at the top, and at local level, declare them in the procedure.
THANKS!