VBA also provides a number of helpful functions and formatting features that
you can use to work with other bases.
Listing 4-8 is an example of all these
features in action.
Listing 4-8
Converting between Numeric Bases
Public Sub ShowBase()
‘ Define the three number bases.
Dim
OctNum As Integer
Dim DecNum As Integer
Dim HexNum As Integer
‘ Define an output string.
Dim Output As String
‘ Assign an octal number.
OctNum = &O110
‘ Assign a decimal number.
DecNum = 110
‘ Assign a hexadecimal number.
HexNum = &H110
‘ Create a heading.
Output = vbTab + vbTab + vbTab + “Oct” + _
vbTab + “Dec” + _
vbTab + “Hex” +
vbCrLf
‘ Create an output string.
Output = Output + “Octal Number:” + _
vbTab + vbTab + Oct$(OctNum) + _
vbTab + CStr(OctNum) + _
vbTab + Hex$(OctNum) + _
vbCrLf + “Decimal Number:” + _
vbTab + vbTab + Oct$(DecNum) + _
vbTab + CStr(DecNum) + _
vbTab + Hex$(DecNum) + _
vbCrLf + “Hexadecimal Number:” + _
vbTab + Oct$(HexNum) + _
vbTab + CStr(HexNum) + _
vbTab + Hex$(HexNum)
‘ Display the actual numbers.
MsgBox Output, _
vbInformation Or vbOKOnly, _
“Data Type Output”
End Sub
The code begins with three integers. It then assigns values to each of these
integers. Notice that the octal
number is set by using the
&O
prefix (that’s the
letter
O
and not a zero), and the hex number is set by using the
&H
prefix.
95
Chapter 4: Storing and Modifying Information
09_046500 ch04.qxp 12/5/06 5:54 PM Page 95
This example also adds a new constant to your list. The
vbTab
constant
adds a tab character to the output string. (See the Visual Basic Constants
help topic for a complete list of VBA constants.) Notice that this example
provides both a header and
some data in the dialog box, which shows how
to display data in a tabular format.
Whenever you want to convert a number to a string, you need to use a con-
version function. This example shows the three
common conversion func-
tions for octal (
Oct$
), decimal (
CStr
), and hex (
Hex$
) numbers. Run this
program to see how the functions interact. Notice that you can see the header
and each of the numbers in different bases.
Performing conversions between numbers and strings
Most
display features, such as the
MsgBox
function and forms, require
strings, even for numbers. When
you work with numeric data, you convert
the data to a string. The preceding “Defining hex and octal values” section
shows some techniques for converting numbers to strings (and vice versa),
but this example is only the beginning. Listing 4-9 demonstrates some of the
essential string-to-number and number-to-string conversion functions.
Do'stlaringiz bilan baham: