Saving VBA Code Best Practice

D

Dan

Hi,
I'm new to VBA coding for Word and a little unsure of the best method
of saving my subroutines in a template. I would like to distribute
this template to internal employees (technical writers).

1. I wrote a couple subroutines that perform different actions. I put
all of them in the ThisDocument node under TemplateProject. Is this
standard practice?

2. I noticed that the subroutines appear in the Macros dialog
(Tools>Macro>Macros) but not in the Organizer. I imagine this is OK,
but what if I want to move the subroutines to a different template
down the road?

3. Also, how can I call my subroutines directly from Word? Should I go
through a separate procedure to create a new Macro that calls them?

Thanks for any guidance!
 
S

Shauna Kelly

Hi Dan

I think the following is usual, although others may have different
practices:

1. In the ThisDocument class, only put code that responds to the document
events such as Document_New, plus, perhaps, any routines that are called by
code in the document events, and not used elsewhere in your file -- and mark
those other routines Private.

2. Put all other code in one or more Modules. You can insert a new one using
Insert > Module and you can re-name it using the Properties window.

Good practice is to have only a very few Public Subs in each module (note
that in VBA all routines are public by default). There are any number of
exceptions to that, but it's the general rule. Any supporting routines
should be marked Private. And, good practice is to group routines into
Modules in some organized way. So, for example, if you have a couple of
routines that work on tables, and one that works on headers and footers,
then create two modules, name them (eg) Tables and HeadersAndFooters, and
put the routines in the appropriate module.

As you learn more, you might also use UserForms and Classes. You can insert
them using the Insert menu.

3. You will only see a macro at Tools > Macros > Macros if it:
- is in a Module (not in ThisDocument, or a UserForm or a Class)
- is a Sub (not a Function)
- is not Private
- does not take any parameters
- is not in a module prefaced with Option Private Module

In this way, you can determine which macros are exposed to the user, and
which are hidden.

Hope this helps.

Shauna Kelly. Microsoft MVP.
http://www.shaunakelly.com/word
 
D

Dan

Hi Shauna,
Thanks so much for your advice. You gave me a clear path and answered
questions I didn't even know I had! By the way, your Word website is
terrifically useful. It's been in my Bookmarks for a few months now,
and I find your articles to provide absolutely the best explanations
of Word's inner workings.

Best,
Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top