Data Types

See Also

Variables are placeholders used to store values; they have names and data types. The data type of a variable determines how the bits representing those values are stored in the computer's memory. When you declare a variable, you can also supply a data type for it. All variables have a data type that determines what kind of data they can store.

By default, if you don't supply a data type, the variable is given the Variant data type. The Variant data type is like a chameleon — it can represent many different data types in different situations. You don't have to convert between these types of data when assigning them to a Variant variable: Visual Basic automatically performs any necessary conversion.

If you know that a variable will always store data of a particular type, however, Visual Basic can handle that data more efficiently if you declare a variable of that type. For example, a variable to store a person's name is best represented as a string data type, because a name is always composed of characters.

Data types apply to other things besides variables. When you assign a value to a property, that value has a data type; arguments to functions also have data types. In fact, just about anything in Visual Basic that involves data also involves data types.

You can also declare arrays of any of the fundamental types.

For More Information   For more information, see the section, "Arrays," later in this chapter. Selecting data types to improve your application's performance is discussed in "Designing for Performance and Compatibility."

Declaring Variables with Data Types

Before using a non-Variant variable, you must use the Private, Public, Dim or Static statement to declare it As type. For example, the following statements declare an Integer, Double, String, and Currency type, respectively:

Private I As Integer
Dim Amt As Double
Static YourName As String
Public BillsPaid As Currency

A Declaration statement can combine multiple declarations, as in these statements:

Private I As Integer, Amt As Double
Private YourName As String, BillsPaid As Currency
Private Test, Amount, J As Integer

Note   If you do not supply a data type, the variable is given the default type. In the preceding example, the variables Test and Amount are of the Variant data type. This may surprise you if your experience with other programming languages leads you to expect all variables in the same declaration statement to have the same specified type (in this case, Integer).

Numeric Data Types

Visual Basic supplies several numeric data types — Integer, Long (long integer), Single (single-precision floating point), Double (double-precision floating point), and Currency. Using a numeric data type generally uses less storage space than a variant.

If you know that a variable will always store whole numbers (such as 12) rather than numbers with a fractional amount (such as 3.57), declare it as an Integer or Long type. Operations are faster with integers, and these types consume less memory than other data types. They are especially useful as the counter variables in For...Next loops.

For More Information   To read more about control structures, see "Introduction to Control Structures" later in this chapter.

If the variable contains a fraction, declare it as a Single, Double, or Currency variable. The Currency data type supports up to four digits to the right of the decimal separator and fifteen digits to the left; it is an accurate fixed-point data type suitable for monetary calculations. Floating-point (Single and Double) numbers have much larger ranges than Currency, but can be subject to small rounding errors.

Note   Floating-point values can be expressed as mmmEeee or mmmDeee, in which mmm is the mantissa and eee is the exponent (a power of 10). The highest positive value of a Single data type is 3.402823E+38, or 3.4 times 10 to the 38th power; the highest positive value of a Double data type is 1.79769313486232D+308, or about 1.8 times 10 to the 308th power. Using D to separate the mantissa and exponent in a numeric literal causes the value to be treated as a Double data type. Likewise, using E in the same fashion treats the value as a Single data type.

The Byte Data Type

If the variable contains binary data, declare it as an array of the Byte data type. (Arrays are discussed in "Arrays" later in this chapter). Using Byte variables to store binary data preserves it during format conversions. When String variables are converted between ANSI and Unicode formats, any binary data in the variable is corrupted. Visual Basic may automatically convert between ANSI and Unicode when:

All operators that work on integers work with the Byte data type except unary minus. Since Byte is an unsigned type with the range 0-255, it cannot represent a negative number. So for unary minus, Visual Basic coerces the Byte to a signed integer first.

All numeric variables can be assigned to each other and to variables of the Variant type. Visual Basic rounds off rather than truncates the fractional part of a floating-point number before assigning it to an integer.

For More Information   For details on Unicode and ANSI conversions, see "International Issues."

The String Data Type

If you have a variable that will always contain a string and never a numeric value, you can declare it to be of type String:

Private S As String

You can then assign strings to this variable and manipulate it using string functions:

S = "Database"
S = Left(S, 4)

By default, a string variable or argument is a variable-length string; the string grows or shrinks as you assign new data to it. You can also declare strings that have a fixed length. You specify a fixed-length string with this syntax:

String * size

For example, to declare a string that is always 50 characters long, use code like this:

Dim EmpName As String * 50

If you assign a string of fewer than 50 characters, EmpName is padded with enough trailing spaces to total 50 characters. If you assign a string that is too long for the fixed-length string, Visual Basic simply truncates the characters.

Because fixed-length strings are padded with trailing spaces, you may find the Trim and RTrim functions, which remove the spaces, useful when working with them.

Fixed-length strings in standard modules can be declared as Public or Private. In forms and class modules, fixed-length strings must be declared Private.

For More Information   See "Ltrim, RTrim Function and Trim Functions" in the Language Reference.

Exchanging Strings and Numbers

You can assign a string to a numeric variable if the string represents a numeric value. It's also possible to assign a numeric value to a string variable. For example, place a command button, text box, and list box on a form. Enter the following code in the command button's Click event. Run the application, and click the command button.

Private Sub Command1_Click()
   Dim intX As Integer
   Dim strY As String
   strY = "100.23"
   intX = strY      ' Passes the string to a numeric 
                  ' variable.
   List1.AddItem Cos(strY)   ' Adds cosine of number in 
                        ' the string to the listbox.
   strY = Cos(strY)         ' Passes cosine to the 
                           ' string variable.
   Text1.Text = strY      ' String variable prints in 
                        ' the text box.
End Sub

Visual Basic will automatically coerce the variables to the appropriate data type. You should use caution when exchanging strings and numbers; passing a non-numeric value in the string will cause a run-time error to occur.

The Boolean Data Type

If you have a variable that will contain simple true/false, yes/no, or on/off information, you can declare it to be of type Boolean. The default value of Boolean is False. In the following example, blnRunning is a Boolean variable which stores a simple yes/no setting.

Dim blnRunning As Boolean
   ' Check to see if the tape is running.
   If Recorder.Direction = 1 Then 
   blnRunning = True
End if

The Date Data Type

Date and time values can be contained both in the specific Date data type and in Variant variables. The same general characteristics apply to dates in both types.

For More Information   See the section, "Date/Time Values Stored in Variants," in "Advanced Variant Topics."

When other numeric data types are converted to Date, values to the left of the decimal represent date information, while values to the right of the decimal represent time. Midnight is 0, and midday is 0.5. Negative whole numbers represent dates before December 30, 1899.

The Object Data Type

Object variables are stored as 32-bit (4-byte) addresses that refer to objects within an application or within some other application. A variable declared as Object is one that can subsequently be assigned (using the Set statement) to refer to any actual object recognized by the application.

Dim objDb As Object
Set objDb = OpenDatabase("c:\Vb5\Biblio.mdb")

When declaring object variables, try to use specific classes (such as TextBox instead of Control or, in the preceding case, Database instead of Object) rather than the generic Object. Visual Basic can resolve references to the properties and methods of objects with specific types before you run an application. This allows the application to perform faster at run time. Specific classes are listed in the Object Browser.

When working with other applications' objects, instead of using a Variant or the generic Object, declare objects as they are listed in the Classes list in the Object Browser. This ensures that Visual Basic recognizes the specific type of object you're referencing, allowing the reference to be resolved at run time.

For More Information   For more information on creating and assigning objects and object variables, see "Creating Objects" later in this chapter.

Converting Data Types

Visual Basic provides several conversion functions you can use to convert values into a specific data type. To convert a value to Currency, for example, you use the CCur function:

PayPerWeek = CCur(hours * hourlyPay)
Conversion
function

Converts an expression to

Cbool Boolean
Cbyte Byte
Ccur Currency
Cdate Date
CDbl Double
Cint Integer
CLng Long
CSng Single
CStr String
Cvar Variant
CVErr Error

Note   Values passed to a conversion function must be valid for the destination data type or an error occurs. For example, if you attempt to convert a Long to an Integer, the Long must be within the valid range for the Integer data type.

For More Information   See the Language Reference for a specific conversion function.

The Variant Data Type

A Variant variable is capable of storing all system-defined types of data. You don't have to convert between these types of data if you assign them to a Variant variable; Visual Basic automatically performs any necessary conversion. For example:

Dim SomeValue      ' Variant by default.
SomeValue = "17"   ' SomeValue contains "17" (a two-
                  ' character string).
SomeValue = SomeValue - 15       ' SomeValue now contains 
                              ' the numeric value 2.
SomeValue = "U" & SomeValue      ' SomeValue now contains 
                     ' "U2" (a two- character string).

While you can perform operations on Variant variables without much concern for the kind of data they contain, there are some traps you must avoid.

In addition to being able to act like the other standard data types, Variants can also contain three special values: Empty, Null, and Error.

The Empty Value

Sometimes you need to know if a value has ever been assigned to a created variable. A Variant variable has the Empty value before it is assigned a value. The Empty value is a special value different from 0, a zero-length string (""), or the Null value. You can test for the Empty value with the IsEmpty function:

If IsEmpty(Z) Then Z = 0

When a Variant contains the Empty value, you can use it in expressions; it is treated as either 0 or a zero-length string, depending on the expression.

The Empty value disappears as soon as any value (including 0, a zero-length string, or Null) is assigned to a Variant variable. You can set a Variant variable back to Empty by assigning the keyword Empty to the Variant.

The Null Value

The Variant data type can contain another special value: Null. Null is commonly used in database applications to indicate unknown or missing data. Because of the way it is used in databases, Null has some unique characteristics:

You can also assign Null with the Null keyword:

Z = Null

You can use the IsNull function to test if a Variant variable contains Null:

If IsNull(X) And IsNull(Y) Then
   Z = Null
Else
   Z = 0
End If

If you assign Null to a variable of any type other than Variant, a trappable error occurs. Assigning Null to a Variant variable doesn't cause an error, and Null will propagate through expressions involving Variant variables (though Null does not propagate through certain functions). You can return Null from any Function procedure with a Variant return value.

Variables are not set to Null unless you explicitly assign Null to them, so if you don't use Null in your application, you don't have to write code that tests for and handles it.

For More Information   For information on how to use Null in expressions, see "Null" in the Language Reference.

The Error Value

In a Variant, Error is a special value used to indicate that an error condition has occurred in a procedure. However, unlike for other kinds of errors, normal application-level error handling does not occur. This allows you, or the application itself, to take some alternative based on the error value. Error values are created by converting real numbers to error values using the CVErr function.

For More Information   For information on how to use the Error value in expressions, see "CVErr Function" in the Language Reference. For information on error handling, see "Debugging Your Code and Handling Errors." For additional information about the Variant data type, see "Advanced Variant Topics."