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.
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.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.
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:- Reading from files
- Writing to files
- Calling DLLs
- Calling methods and properties on objects
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.
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.
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
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.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.
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.