9.3. Using Functions to Convert Data from One Type to Another

VBA provides a full set of functions for converting data from one data type to another. These functions fall into two distinct groups: simple data conversion and more complex data conversion.

Table 9.1 lists VBA's functions for simple data conversion.

Table 9.1. VBA's Functions for Simple Data Conversion
Function(Arguments)Data Type Returned
CBool(number)Boolean
CByte(expression)Byte
CCur(expression)Currency
CDate(expression)Date
CDbl(expression)Double
CInt(expression)Integer
CLng(expression)Long
CSng(expression)Single
CStr(expression)String
CVar(expression)Variant

For example, the following statements declare the untyped variable varMyInput and the Integer variable intMyVar and then display an input box prompting the user to enter an integer. In the third statement, the user's input is assigned to varMyInput, which automatically becomes a Variant/String. The fourth statement uses the CInt function to convert varMyInput to an integer, assigning the result to intMyVar. The fifth statement compares intMyVar to 10, converts the result to Boolean by using the CBool function, and displays the result (True or False) in a message box.

Dim varMyInput
Dim intMyVar As Integer
varMyInput = InputBox("Enter an integer:", "10 Is True, Other Numbers Are False")
intMyVar = CInt(varMyInput)
MsgBox CBool(intMyVar = 10)

Table 9.2 lists VBA's functions for more complex data conversion.

9.3.1. Using the Asc Function to Return a Character Code

The Asc function returns the character code for the first character of a string. Character codes are the numbers by which computers refer to letters. For example, the character code for a capital A is 65 and for a capital B is 66; a lowercase a is 97, and a lowercase b is 98.

The syntax for the Asc function is straightforward:

Asc(string)

Here, string is any string expression. For example, Asc("A") returns 65.

The following statements use the Asc function to return the character code for the first character of the current selection in the active document and display that code in a message box:

strThisCharacter = Asc(Selection.Text)
MsgBox strThisCharacter, vbOKOnly, "Character Code"

9.3.2. Using the Val Function to Extract a Number from the Start of a String

The Val function converts the numbers contained in a string into a numeric value. Val follows these rules:

  • It reads only numbers in a string.

  • It starts at the beginning of the string and reads only as far as the string contains characters that it recognizes as numbers.

  • It ignores tabs, line feeds, and blank spaces.

  • It recognizes the period as a decimal separator but not the comma.

Table 9.2. VBA's Functions for Complex Data Conversion
Function(Arguments)Returns
Asc(string)The ANSI character code for the first character in the string.
Chr(number)The string for the specified character code (a number between 0 and 255).
Format(expression,format)A variant containing expression formatted as specified by format. (You'll see how Format works in "Using the Format Function to Format an Expression," later in the chapter.)
Hex(number)A string containing the hexadecimal value of number.
Oct(number)A string containing the octal value of number.
RGB(number1,number2,number3)A Long integer representing the color value specified by number1, number2, and number3.
QBColor(number)A Long containing the RGB value for the specified color.
Str(number)A Variant/String containing a string representation of number.
Val(string)The numeric portion of string; if string does not have a numeric portion, Val returns 0.

This means that if you feed Val a string consisting of tabbed columns of numbers, such as the second line here, it will read them as a single number (in this case, 445634.994711):

Item#   Price  Available   On Order  Ordered
4456    34.99      4          7        11

If, however, you feed it something containing a mix of numbers and letters, Val will read only the numbers and strings recognized as numeric expressions (for example, Val("4E5") returns 400000, because it reads the expression as exponentiation). For example, if fed the address shown here, Val returns 8661, ignoring the other numbers in the string (because it stops at the L of Laurel, the first character that isn't a number, a tab, a line feed, or a space):

8661 Laurel Avenue Suite 3806, Oakland, CA 94610

The syntax for Val is straightforward:

Val(string)

Here, string is a required argument consisting of any string expression.

The following statement uses Val to return the numeric variable StreetNumber from the string Address1:

StreetNumber = Val(Address1)

9.3.3. Using the Str Function to Convert a Value to a String

Just as you can convert a string to a value, you can also convert a value to a string. You'll need to do this when you want to concatenate the information contained in a value with a string—if you try to do this simply by using the + operator, VBA attempts to perform a mathematical operation rather than concatenation.

For example, suppose you've declared a String variable named strYourAge and a numeric variable named intAge. You can't use a strYourAge + intAge statement to concatenate them, because they're different types; you first need to create a string from the intAge variable and then concatenate that string with the strYourAge string. (Alternatively, you can use the & operator to concatenate the two variables.)

To convert a value to a string, use the Str function. The syntax for the Str function is this:

Str(number)

Here, number is a variable containing a numeric expression (such as an Integer data type, a Long data type, or a Double data type).

The following short procedure provides an example of converting a value to a string:

Sub Age()
    Dim intAge As Integer, strYourAge As String
    intAge = InputBox("Enter your age:", "Age")
    strYourAge = "Your age is" & Str(intAge) & "."
    MsgBox strYourAge, vbOKOnly + vbInformation, "Age"
End S

9.3.4. Using the Format Function to Format an Expression

The Format function is a powerful tool for changing numbers, dates and times, and strings into the format in which you need them.

The syntax for the Format function is as follows:

Format(expression[, format[, firstdayofweek[, firstweekofyear]]])

These are the components of the syntax:

  • expression is any valid expression.

  • format is an optional argument specifying a named format expression or a user-defined format expression. More on this in a moment.

  • firstdayofweek is an optional constant specifying the day that starts the week (for date information): The default setting is vbSunday (1), but you can also set vbMonday (2), vbTuesday (3), vbWednesday (4), vbThursday (5), vbFriday (6), vbSaturday (7), or vbUseSystem (0; uses the system setting).

  • firstweekofyear is an optional constant specifying the week considered first in the year (again, for date information):

ConstantValueYear Starts with Week
vbUseSystem0Use the system setting.
vbFirstJan11The week in which January 1 falls (the default setting).
vbFirstFourDays2The first week with a minimum of four days in the year.
vbFirstFullWeek3The first full week (7 days) of the year.

You can define your own formats for the Format function as described in the following sections if none of the predefined numeric formats (described next) suits your needs.

9.3.4.1. Using Predefined Numeric Formats

Table 9.3 lists the following predefined numeric formats that you can use with the Format function.

Table 9.3. Predefined Numeric Formats
Format NameExplanationExample
General NumberThe number is displayed with no thousand separator.124589
CurrencyThe number is displayed with two decimal places, a thousand separator, and the currency symbol appropriate to the system locale.$1,234.56
FixedThe number is displayed with two decimal places and at least one integer place.5.00
StandardThe number is displayed with two decimal places, at least one integer place, and a thousand separator (when needed).1,225.00
PercentThe number is displayed multiplied by 100, with two decimal places, and with a percent sign.78.00%
ScientificThe number is displayed in scientific notation.5.00E + 00
Yes/NoA non-zero number is displayed as Yes; a zero number is displayed as No.Yes
True/FalseA non-zero number is displayed as True; a zero number is displayed as False.False
On/OffA non-zero number is displayed as On; a zero number is displayed as Off.Off

For example, the following statement returns $123.45:

Format("12345", "Currency")

9.3.4.2. Creating a Numeric Format

If none of the predefined numeric formats suits your needs, you can create your own numeric formats by using your choice of combination of the characters listed in Table 9.4.

Table 9.4. Characters for Creating Your Own Number Formats
CharacterExplanation
[None]Displays the number without any formatting. (You won't usually want to use this option.)
0Placeholder for a digit. If there's no digit, VBA displays a zero. If the number has fewer digits than you use zeroes, VBA displays leading or trailing zeroes as appropriate.
#Placeholder for a digit. If there's no digit, VBA displays nothing.
.Placeholder for a decimal. Indicates where the decimal separator should fall. The decimal separator varies by locale (for example, a decimal point in the United States, a comma in Germany).
%Placeholder for a percent character. VBA inserts the percent character and multiplies the expression by 100.
,Thousand separator (depending on locale, a comma or a period).
:Time separator (typically a colon, but again this depends on the locale).
/Date separator. (Again, what you'll see depends on the locale.)
E- E+ e- e +Scientific format: E- or e- places a minus sign next to negative exponents. E+ or e+ places a minus sign next to negative exponents and places a plus sign next to positive exponents.
-+ $ ( )Displays a literal character.
[character]Displays the literal character.
' '[string]' 'Displays the literal character. Use Chr(34) (the character code for double quotation marks) to provide the double quotation marks.

For example, the following statement returns a currency formatted with four decimal places:

Format("123456", "$00.0000")

9.3.4.3. Creating a Date or Time Format

Similarly, you can create your own date and time formats by mixing and matching the characters listed in Table 9.5.

Table 9.5. Characters for Creating Your Own Date and Time Formats
CharacterExplanation
:Time separator (typically a colon, but this depends on the locale).
/Date separator (also locale-dependent).
cDisplays the date (if there is a date or an integer value) in the system's short date format and the time (if there is a date or a fractional value) in the system's default time format.
dDisplays the date (1 to 31) without a leading zero for single-digit numbers.
ddDisplays the date with a leading zero for single-digit numbers (01 to 31).
dddDisplays the day as a three-letter abbreviation (Sun, Mon, Tue, Wed, Thu, Fri, Sat) with no period.
ddddDisplays the full name of the day.
dddddDisplays the complete date (day, month, and year) in the system's short date format.
ddddddDisplays the complete date (day, month, and year) in the system's long date format.
aaaaDisplays the full, localized name of the day.
wDisplays an integer from 1 (Sunday) to 7 (Monday) containing the day of the week.
wwDisplays an integer from 1 to 54 giving the number of the week in the year. The number of weeks is 54 rather than 52 because most years start and end with partial weeks rather than having 52 start-to-finish weeks.
mDisplays an integer from 1 to 12 giving the number of the month without a leading zero on single-digit months. When used after h, returns minutes instead of months.
mmDisplays a number from 01 to 12 giving the two-digit number of the month. When used after h, returns minutes instead of months.
mmmDisplays the month as a three-letter abbreviation (except for May) without a period.
mmmmDisplays the full name of the month.
ooooDisplays the full localized name of the month.
qDisplays a number from 1 to 4 giving the quarter of the year.
yDisplays an integer from 1 to 366 giving the day of the year.
yyDisplays a number from 00 to 99 giving the two-digit year.
yyyyDisplays a number from 0100 to 9999 giving the four-digit year.
hDisplays a number from 0 to 23 giving the hour.
HhDisplays a number from 00 to 23 giving the two-digit hour.
NDisplays a number from 0 to 60 giving the minute.
NnDisplays a number from 00 to 60 giving the two-digit minute.
SDisplays a number from 0 to 60 giving the second.
SsDisplays a number from 00 to 60 giving the two-digit second.
tttttDisplays the full time (hour, minute, and second) in the system's default time format.
AM/PMUses the 12-hour clock and displays AM or PM as appropriate.
am/pmUses the 12-hour clock and displays am or pm as appropriate.
A/PUses the 12-hour clock and displays A or P as appropriate.
a/pUses the 12-hour clock and displays a or p as appropriate.
AMPMUses the 12-hour clock and displays the AM or PM string literal defined for the system.

For example, the following statement returns Saturday, April 01, 2008:

Format(#4/1/2008#, "dddddd")

9.3.4.4. Creating a String Format

Format also lets you create custom string formats using the options shown in Table 9.6.

For example, the following statement assigns to strUser a string consisting of four spaces if there is no input in the input box:

strUser = Format(InputBox("Enter your name:"), "@@@@")

9.3.5. Using the Chr Function and Constants to Enter Special Characters in a String

To add special characters (such as a carriage return or a tab) to a string, specify the built-in constant (for those special characters that have built-in constants defined) or enter the appropriate character code using the Chr function. The syntax for the Chr function is straightforward:

Chr(charactercode)

Table 9.6. Characters for Creating Your Own String Formats
CharacterExplanation
@Placeholder for a character. Displays a character if there is one and a space if there is none.
&Placeholder for a character. Displays a character if there is one and nothing if there is none.
<Displays the string in lowercase.
>Displays the string in uppercase.
!Causes VBA to fill placeholders from left to right instead of from right to left (the default direction).

Here, charactercode is a number that identifies the character to add.

Table 9.7 lists the most useful character codes and character constants.

Say that you wanted to build a string containing a person's name and address from individual strings containing items of that information, and that you also wanted the individual items separated by tabs in the resulting string so that you could insert the string into a document and then convert it into a table. To do this, you could use a statement like the following one. Here, VBA uses a For... Next loop to repeat the action until the counter i reaches the number stored in the variable intNumRecords:

For i = 1 to intNumRecords
    AllInfo = FirstName & vbTab & MiddleInitial & vbTab _
    & LastName & vbTab & Address1 & vbTab & Address2 _
        & vbTab & City & vbTab & State & vbTab & Zip _
        & vbTab & BusinessPhone & vbTab & HomePhone _
        & vbTab & BusinessEMail & vbTab & HomeEMail & vbCr
    Selection.TypeText AllInfo
Next i

Table 9.7. VBA Character Codes and Character Constants
CodeBuilt-in Character ConstantCharacter
Chr(9)vbTabTab
Chr(10)vbLfLine feed
Chr(11)vbVerticalTabSoft return (Shift+Enter)
Chr(12)vbFormFeedPage break
Chr(13)vbCrCarriage return
Chr(13)+Chr(10)vbCrLfCarriage return/line feed combination
Chr(14)Column break
Chr(34)Double straight quotation marks (")
Chr(39)Single straight quote mark/apostrophe (')
Chr(145)Opening single smart quotation mark (')
Chr(146)Closing single smart quotation mark/apostrophe (')
Chr(147)Opening double smart quotation mark (")
Chr(148)Closing double smart quotation mark (")
Chr(149)Bullet
Chr(150)En dash
Chr(151)Em dash

The second line (split here over five physical lines) assigns data to the string AllInfo by concatenating the strings FirstName, MiddleInitial, LastName, and so on with tabs — vbTab characters — between them. The final character added to the string is vbCr (a carriage-return character), which creates a new paragraph.

The third line enters the AllInfo string into the current document, thus building a tab-delimited list containing the names and addresses. This list can then be easily converted into a table whose columns each contain one item of information: the first column contains the FirstName string, the second column the MiddleInitial string, and so on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.35.158