Re: Working with SUBs
- From: "Jonathan West" <jwest@xxxxxxxx>
- Date: Wed, 5 Sep 2007 19:14:03 +0100
"Rick Charnes" <rickxyz--nospam.zyxbadcharnes@xxxxxxxxxxxxxxx> wrote in message news:MPG.2148925e5a0696ce9899ad@xxxxxxxxxxxxxxxxxxxxxxx
Kinda new to writing subroutines within VBA. I didn't realize that all
the module-level variables declared in the body of the procedure are not
available to you in the SUB.
Before you start confusing yourself and everyone else here, let's get some terminology straight.
Module-level variables are declared *before* the first Sub or Function in the module. They are declared using the keyword Private rather than Dim. A module level variable can be used by any routine within the same module.
Global variables are also declared before the first Sub or Function of a module, but using the Public keyword. A global variable can be used by any routine in any module of the project.
Procedure-level variables are declared after the Sub or Function statement at the start of a procedure, and are only available within that procedure.
I guess I have to pass any that are needed
in the SUB, as arguments?
That is usually the best way.
Is there another technique?
Yes, you can use global or module level variables, but I would recommend being very sparing with their use. If you declare a variable locally and pass it as a parameter to another routine, you know that there is only one point at which the two routines interact. With a module-level or global variable, any routine can affect the operation of any other simply by changing the value of a common variable, and as there is no limitation as to how and where this can happen, bug-hunting can take on needle-in-a-haystack dimensions
You might be interested in this article which describes some additional techniques for writing maintainable code.
The art of defensive programming
http://www.word.mvps.org/FAQs/MacrosVBA/MaintainableCode.htm
--
Regards
Jonathan West - Word MVP
www.intelligentdocuments.co.uk
Please reply to the newsgroup
.
- References:
- Working with SUBs
- From: Rick Charnes
- Working with SUBs
- Prev by Date: RE: Working with SUBs
- Next by Date: Re: Macro list drop down
- Previous by thread: RE: Working with SUBs
- Next by thread: Need Macro to UnBold TOC
- Index(es):
Relevant Pages
|