MS-Word / General Formatting

Using static variables

A static variable is a variable whose value is preserved between executions of the procedure in which it's declared. You can find many excellent uses for static variables in Word macros. For example, you may use a static variable to temporarily keep track of text entered by the user, to remember the location in the document where an operation was performed, or to keep track of actions taken since the last time the macro was run.

To create a static variable, use the Static keyword rather than the Dim keyword, like this:

Static iCaseCount As Integer

You can use static variables only in procedures. You can't create a static variable at the module level.

Using Option Explicit

Unlike in many other programming languages, such as Java or C#, you don't have to define variables before you can use them in VBA. The first time you use a variable in a VBA macro, the variable is automatically defined.

Most experienced programmers consider not having to define variables to be the major weakness in BASIC and all its dialects, including VBA and Visual Basic. The trouble is that you never know when you've misspelled a variable name, because if you misspell one, VBA assumes that you want to create a new variable. Suppose at the start of a macro you ask the user to enter a string value and you store the value entered by the user in a variable named InputString. Then later in the macro, you use the variable in a statement but misspell it InputStrign. Does VBA point out your error? No. It just assumes that you want to create a new variable named InputStrign. This InputStrign variable is given a default value of "" rather than the value entered by the user.

This type of problem is quite common in VBA programming. Whenever you're faced with a macro that looks like it should work but doesn't, carefully double-check all variable names for misspellings.

You can avoid the problem of misspelled variable names by adding the following line to the beginning of your VBA module:

Option Explicit

This line forces you to declare variables before you use them. Then if you use a variable that you haven't declared, you see an error message.

[Previous] [Contents] [Next]