30.04.2017 Views

4523756273

Create successful ePaper yourself

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

Chapter 7: Essential VBA Language Elements<br />

99<br />

VBA has a variety of built-in data types. Table 7-1 lists the most common<br />

types of data that VBA can handle.<br />

Table 7-1<br />

VBA’s Built-In Data Types<br />

Data Type Bytes Used Range of Values<br />

Boolean 2 True or False<br />

Integer 2 –32,768 to 32,767<br />

Long 4 –2,147,483,648 to 2,147,483,647<br />

Single 4 –3.402823E38 to 1.401298E45<br />

Double (negative) 8 –1.79769313486232E308 to<br />

–4.94065645841247E-324<br />

Double (positive) 8 4.94065645841247E–324 to<br />

1.79769313486232E308<br />

Currency 8 –922,337,203,685,477.5808 to<br />

922,337,203,685,477.5807<br />

Date 8 1/1/100 to 12/31/9999<br />

String 1 per char Varies<br />

Object 4 Any defined object<br />

Variant Varies Any data type<br />

User defined Varies Varies<br />

In general, choose the data type that uses the smallest number of bytes but<br />

can still handle all the data you want to store in the variable.<br />

Loop counters are often declared as integers. If you use the counter in order<br />

to loop through rows in the worksheet, your program might just error out!<br />

Why? Integers cannot be larger than 32,767. Beginning with Excel 2007, worksheets<br />

have many more rows (1,048,576 to be exact). Instead, declare such<br />

loop counters as Long.<br />

Declaring and scoping variables<br />

If you read the previous sections, you now know a bit about variables and<br />

data types. In this section, you discover how to declare a variable as a certain<br />

data type.<br />

If you don’t declare the data type for a variable you use in a VBA routine, VBA<br />

uses the default data type: Variant. Data stored as a variant acts like a chameleon;<br />

it changes type depending on what you do with it. For example, if a variable<br />

is a Variant data type and contains a text string that looks like a number

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

Saved successfully!

Ooh no, something went wrong!