18.11.2014 Views

Microsoft Office

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

VBA Examples 44<br />

If you don’t declare a variable, Excel uses the Variant data type. In general, the best technique is to use<br />

the data type that uses the smallest number of bytes yet can still handle all the data assigned to it. An exception<br />

is when you’re performing floating-point calculations. In such a case, it is always best to use the<br />

Double data type (rather than the Single data type) to maintain maximum precision.<br />

When VBA works with data, execution speed is a function of the number of bytes that VBA has at its disposal.<br />

In other words, the fewer bytes that are used by data, the faster VBA can access and manipulate the<br />

data.<br />

To declare a variable, use the Dim statement before you use the variable for the first time. For example, to<br />

declare the variable Units as an integer, use the following statement:<br />

Dim Units as Integer<br />

To declare the variable UserName as a string, use the following statement:<br />

Dim UserName as String<br />

If you declare a variable within a procedure, the declaration is valid only within that procedure. If you<br />

declare a variable outside of any procedures (but before the first procedure), the variable is valid in all procedures<br />

in the module.<br />

If you use an object variable (as described in “Simplifying object references,” earlier in this chapter), you can<br />

declare the variable as the appropriate object data type. The following is an example:<br />

Dim Rate as Range<br />

Set Rate = Workbooks(“MyBook.xlsx”).Worksheets(“Sheet1”).Range(“IntRate”)<br />

To force yourself to declare all the variables that you use, insert the following statement at the top of your<br />

module:<br />

Option Explicit<br />

If you use this statement, Excel displays an error message if it encounters a variable that hasn’t been<br />

declared. After you get into the habit of correctly declaring all your variables, you will find that it helps<br />

eliminate errors and makes spotting errors easier.<br />

769

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!