Declare A Variable

You can use variable declaration to make your VBA code run much more efficiently. By definition, variable declaration means that you specify the data type of the variable when you declare the variable. In other words, if you intend for the variable to contain only integer values, you declare an integer variable.

Unlike some programming languages, VBA lets you use variables that have not been declared. However, if you misspell a variable within your code, VBA may treat the misspelled variable as a totally different variable. For example, if you use the variable MthRent throughout your code and inadvertantly type it as MnthRent, VBA sees it as a new variable and assumes that MthRent and MnthRent are two different variables. To ensure that variables are always properly declared, use the Option Explicit statement as the first statement in a module before your type any procedure code.

You can set the Require Variable Declaration option in the Visual Basic Editor to ensure that variables are always declared for all created procedures. If you select this option, the Visual Basic Editor places the Option Explicit statement at the top of each created module. You can select the Require Variable Declaration check box on the Editor dialog within the Visual Basic Editor.

Even if the variable is declared, you should also type it as part of the declaration. VBA treats all variables without a data type as variants. A variant is VBA's all-purpose data type because it can essentially contain any type of data. In fact, the same variable can contain an integer value at one point and a string value at another location within the same module. Because VBA is forced to interogate the value in the variant variables to determine the type of data, your code becomes less efficient when you do not specify the data type.

DECLARE A VARIABLE

I Type a question For help

5heet2 (5heet2) Sheet3 (5heet3)

B-Ö Modules -«ft Modulel -«ft Module2 Modules -«ft ModuM -«ft Modules

Module6 Module 3

Alphabetic | categorized |

Modules

Module6 Module 3

Alphabetic | categorized |

Modules

-inlxl

Calcul ate_Total

Suto Calculate Total (J

End Fun

Sub Create Variable t) |Dira|lJcwVai| |

^ Type Option Explicit at the top of the module.

0 Position the cursor after the Sub statement.

_Q Type the name of the variable.

I Type a question For help

-inlxl

Q Type As after the variable name.

-0 Type your variable data type.

0 0

Post a comment