Conversion Functions
Visual Basic will usually try to automatically convert variables from one type to another, but sometimes it gets confused about what the programmer really wants. First, Lets explore the variable types that Visual Basic gives us.
Variable Type | Description |
---|---|
Boolean | 2-bytes, contains the special values True or False |
Byte | 1-byte, unsigned integer 0 to 255 |
Currency | 8-byte fixed-point. Stores 4 digits after the decimal point. Stores approx +/- 922 trillion |
Date | 8-byte date/time value from 1/1/100 to 12/31/9999. Dates are stored internally as a Double Precision floating point number. |
Double | 8-byte floating point number (-1.79E_308 to 1.79E+308) |
Integer | 2-byte integer, stores +/- 32K |
Long | 4-byte integer, stores +/- 2 billion |
Object | A 32-bit (4 byte) address that refers to the location of an object |
Single | 4-byte floating point number (-3.40E38 to 3.40E+38) |
String | Variable-length: 10 bytes + string length, holds up to 2 billion chars |
Variant | Can hold any native data type, object reference, and special values (Error, Empty, and Null.) |
When in a situation where Visual Basic cannot automatically convert a variable type to the desiered type, use the appropriate conversion function described below.
Variable Type | Conversion Function |
---|---|
Boolean | CBool([expr]) |
Byte | CByte([expr]) |
Currency | CCur([expr]) |
Date | CDate[expr]) |
Double | CDbl([expr]) |
Integer | CInt([expr]) |
Long | CLng([expr]) |
Object | Cannot convert to an Object type. |
Single | CSng([expr]) |
String | CStr([expr]) |
Variant | Cannot convert to a Variant type. |
Other Conversion Functions
Asc([string]))
Returns the ANSI code (Integer) value of the first character in a string.
Example:
' store the result of Asc in integer form.
Dim myCode as Integer
myCode = Asc("A")
' myCode = 65
myCode = Asc("a")
' myCode = 97
Dim myCode as Integer
myCode = Asc("A")
' myCode = 65
myCode = Asc("a")
' myCode = 97
Hex([expr]))
Returns the hexadecimal value of a specified expression.
Example:
' store the hex result in a string form.
Dim myHex as String
myHex = Hex(10)
' myHex = A
myHex = Hex(460)
' myHex = 1CC
Dim myHex as String
myHex = Hex(10)
' myHex = A
myHex = Hex(460)
' myHex = 1CC
Oct([expr]))
Returns the octal value of a specified expression.
Example:
' store the octal result in a string form.
Dim myOct as String
myOct = Oct(5)
' myOct = 5
myOct = Oct(400)
' myOct = 620
Dim myOct as String
myOct = Oct(5)
' myOct = 5
myOct = Oct(400)
' myOct = 620