Types of VariablesOkay, you know what a variable does and how to name it. But what can you store in a variable? The simple answer is: almost anything. A variable can hold a number; a string of text; or a reference to an object, such as a form, control, or database. Each type of variable has its own memory requirements and is designed to work efficiently with different types of information. Therefore, you cannot store a string like "Hello" in a variable that you declare as an integer. Table 8.2 shows some of the standard variable types that are available in Visual Basic. The table also shows the range of values that the variable can hold and the amount of memory required. Variables with smaller memory requirements should be used wherever possible to conserve system resources. |
|
Table 8.2 - Variables Store Many Types of Information
Type |
Stores |
Memory Requirement |
Range of Values |
Integer | Whole numbers | Two bytes | -32,768 to +32,767 |
Long | Whole numbers | Four bytes | (approximately) +/- 2 billion |
Single | Decimal numbers | Four bytes | +/- 1E-45 to 3E38 |
Double | Decimal numbers | Eight bytes | +/- 5E-324 to 1.8E308 |
Currency | Numbers with up to 15 digits left of the decimal and four digits right of the decimal |
Eight bytes | +/- 9E14 |
String | Text information | One byte per character | Up to 65,400 characters for fixed- length string and up to 2 billion characters for dynamic strings |
Byte | Whole numbers | One byte | 0 to 255 |
Boolean | Logical values | Two bytes | True or False |
Date | Date and time information | Eight bytes | 1/1/100 to 12/31/9999 |
Object | Instances of classes; OLE objects | Four bytes | N/A |
Variant | Any of the types | 16 bytes + 1 byte per character | N/A |
In addition to the preceding variable
typesyou also can create user-defined types to meet your needs. Consider the
following code segment, which demonstrates the declaration and use of a user-defined type:Private Type Point x As Integer y As Integer End Type Private Sub Command1_Click() Dim MyPoint As Point MyPoint.x = 3 MyPoint.y = 5 End Sub As you can see from the sample, you declare a new type by using the Type statement. Note that types must be defined in the general declarations section; in this case, we have defined a private type called Point within a form. To create a variable of the new type, you use the Dim statement just as you would with any other type. The parts of a type are accessed via dot notation. As you know, there are some specialized types to deal with databases (such as Database, Field, and Recordset). Visual Basic knows about these other data types when you add a reference to a type library. A type library is a DLL or other file that makes these types available to your program. |
|
![]() |
![]() |
|||