Visual Basic in 12 Easy Lessons vel13.htm

Previous Page TOC Next Page



Lesson 7, Unit 13


The Built-In Functions



What You'll Learn


If you want to build a house, you'll probably buy prefabricated windows and pre-hung doors instead of framing and hanging them yourself. Unless you want to spend extra time doing the work that you don't have to do, using the prefabricated windows and pre-hung doors makes quick work of those housing elements and allows you to concentrate your energies on the more esthetic items (such as talking your spouse into allowing you to partition two-thirds of the master bedroom for a great computer work area...).

Visual Basic's built-in functions save you all kinds of programming time just as the pre-built housing parts do when home building. The built-in functions work like miniature programs that perform common tasks so that you can concentrate your efforts elsewhere. If, for instance, you need to round a single-precision value to an integer, Visual Basic supplies not one but three built-in functions that round numbers to integer values.



Tip: You've already seen several built-in functions in this book, such as Val() and Chr$(). Usually, though not always, a function that contains a dollar sign after its name is a string function, and a function without a dollar sign in its name is a numeric function. This unit teaches you about both numeric and string functions.


A Function Review


Concept: Functions accept one or more arguments and do work with those arguments. The function then returns a single value.

When you use a function inside a Visual Basic statement, it is said that you're calling a function. For example, the following statement calls the Val() function:


Num = Val(txtAmt.Text) ' Convert entry to number


Definition: An argument is a value that you pass to a function.

The parentheses after a function name hold one or more arguments. In the preceding statement, txtAmt.Text is the argument. Some functions, such as Val(), accept only one argument. Some functions accept more than one argument. Some functions don't require any arguments, and for those functions, the parentheses are optional. The arguments inside the parentheses are often called the argument list. A function can require none, one, or several arguments.

When you specify function arguments, you are passing the arguments to the function. The function works on the argument values that you pass to the function and produces some sort of value from the arguments. As Figure 13.1 illustrates, you send a function one or more arguments and the function, after using the arguments in the argument list, is said to return a value. That value is the answer to the function, more commonly called the return value. Functions are said to receive arguments and return a value.

Figure 13.1. A function works on its arguments and returns one value.



Note: It's worth making this very clear: A function always returns a single value and never more. Although a function's argument list can sometimes contain five or more arguments, a function never returns more than one value.

If a function requires more than one argument, you'll separate those arguments by one or more commas. For example, here is a function named Right$() that requires two arguments, MyName and 10, in its argument list:


Last = Right$(MyName, 10) ' Strip off last name

You'll always have to do something with a function's return value. Here are some things that you might do with a return value:

Basically, anything that you might do with a variable or a constant, you'll do with a function's return value. For example, you learned in Unit 7 how Val() works. Val() converts its string (or variant) argument to a number. The converted number is Val()'s return value. Val() will convert its argument to a single, return value; therefore, you can't place Val() on a line by itself like this:


Val(UserAddress) ' Invalid!

Val() will accept the string named UserAddress and convert that string to a number. You must make sure that the program does something with that number! The function is just a predefined, built-in routine, supplied for you by Visual Basic, which operates on the argument list and returns a value that you've got to do something with. Here are four uses of Val() that use the return value in different ways:


lblHouseNum.Caption = Val(UserAddress) ' To a label


MyHouseNum = Val(UserAddress) ' To a variable
OldAge = 65 + Val(txtAge.Text) ' A calculation
Last = Right$(UserName, Val(Ans)) ' Another function

An argument might even be an expression. The following Val() function first concatenates the string expression used as the argument, and then returns the numerically converted value of that string argument:


Number = Val(aStr1 & aStr2)


Note: The argument list's data type doesn't always match the function's return value data type. For example, a function might take a string argument and return a number. A function might require both a string and a numeric argument, and return a string.

The built-in functions never change their arguments. The built-in functions use their arguments to create a new value: the return value.

Review: There are several built-in functions in Visual Basic that your programs can call. Programs that call functions must do something with the return values from those functions. A function might require one argument or more. If you send an argument list to a function, that function operates on those arguments and returns a single value based on the argument list.

The Numeric Functions


Concept: Several numeric functions work to save you programming time when you're working with numbers. There are conversion functions, scientific functions, and trigonometric functions.

As you read through the following pages, don't worry about memorizing every function. Try to get a general idea of the kinds of functions supplied by Visual Basic. The functions work to save you time. If you need to convert a number or compute a standard formula, the chances are great that Visual Basic includes a function that does the work for you. For example, there is no reason to write an advanced trigonometric sine function, because Microsoft already wrote one for you.



Note: You don't have to be a math lover to use and appreciate the Visual Basic numeric functions. Actually, the less you like math, the more you'll appreciate the fact that Visual Basic supplies all these functions for you so that you never have to write the code to accomplish the same thing.


Converting Numbers


Visual Basic supplies three functions that convert single-precision and double-precision numbers to integer values. When writing applications, you might need to round numbers down or up to their nearest integers. Table 13.1 contains the three integer conversion functions.

Table 13.1. The integer conversion functions.

Function Description
CInt() Rounds fractional values of .5 and more to the next highest integer
Fix() Truncates the fractional portion
Int() Rounds the number down to the integer less than or equal to its arguments

Both Fix() and Int() treat positive integers the same way. Both of the following statements return and store 14:


ans1 = Int(14.6)

ans2 = Fix(14.6)

The Fix() and Int() functions behave differently for negative numbers. The remarks to the right of the following statements indicate the functions' return values:


ans3 = Int(-14.6) ' Stores -15

ans4 = Fix(-14.6) ' Stores -14

The negative number less than or equal to -14.6 is -15; hence, the return values for Int() shown in the first statement's remark.

The CInt() function returns truly rounded numbers, as shown here:


ans5 = CInt(14.1) ' Stores 14

ans6 = CInt(14.6) ' Stores 15

ans7 = CInt(-14.1) ' Stores -14

ans8 = 
CInt(-14.8) ' Stores -15

There are functions similar to CInt() that convert arguments of any data type to any other data type. Table 13.2 contains the rest of the data conversion functions.

Table 13.2. The data type conversion functions.

Function Description
CCur() Converts the argument to an equivalent currency data type
CDbl() Converts the argument to an equivalent double-precision data type.
CLng() Converts the argument to an equivalent long integer data type
CSng() Converts the argument to an equivalent single-precision data type
CStr() Converts the argument to an equivalent string data type
CVar() Converts the argument to an equivalent variant data type


Caution: If the converted argument won't fit in the target data type, Visual Basic issues the Overflow error message shown in Figure 13.2. You've got to make sure, perhaps through an initial If statement, that the argument fits within the range of the converted data type.

Normally, the following assignment stores .1428571 in the label named lblValue:


lblValue.Caption = (1 / 7) ' Assigns .1428571

The following, however, adds precision to the answer for a more accurate calculation:


lblValue.Caption = CDbl(1 / 7) ' Assigns .142857142857143

Figure 13.2. Don't overflow the target data type.



Don't even mention other bases!: If you really want to get fancy with numeric conversions, Visual Basic supports four functions that convert their decimal base-10 arguments to octal (base-8) and hexadecimal (base-16) return values. You'll want to use these functions if you write advanced applications that deal with other number bases.
The two hexadecimal functions, Hex() and Hex$(), convert their numeric arguments to a variant and string hexadecimal value, respectively. The two octal functions, Oct() and Oct$(), convert their numeric arguments to a variant and string octal value, respectively.
If you think that you won't use these functions, forget them! These functions, especially the hexadecimal functions, come in handy for programmers who write system-level applications such as memory- and disk-maintenance programs.


The Asc() function converts its string argument to a corresponding ASCII table value. Generally, you'll pass a one-character string (or a variant that can equate to a string) value to Asc(). If the argument contains more than one character, Asc() ignores all characters following the first one.

The following statement stores the number 65 in the numeric variable named Initial because 65 is the uppercase letter A in the ASCII table:


Initial = Asc("A")

Table 13.3 lists the remaining math functions that Visual Basic provides. Many of the functions are scientific and mathematical. You may not need any or all of the functions unless you write heavy, math-intensive applications.

Table 13.3. The scientific and mathematical functions.

Function Description
Abs() Returns the absolute value of the argument
Atn() Returns the computed arc tangent of the argument expressed in radians
Cos() Returns the computed cosine of the argument expressed in radians
Exp() Returns the base of the natural logarithm argument
Log() Returns the natural logarithm of the argument.
Sin() Returns the computed sine of the argument expressed in radians
Sqr() Returns the square root of the argument
Tan() Returns the computed tangent of the argument expressed in radians


Tip: If you compute trigonometric values on arguments expressed as degrees instead of radians, multiply the argument by pi and divide by 180. The following expression assigns the sine of 38 degrees to a variable named sVal:



sVal = Sin(38 * 3.14159 / 180)

Review: The numeric functions will help you write programs when you need to include mathematical calculations in the code. Many business, graphics, and research applications sometimes utilize complex routines, and Visual Basic's math functions will help shorten your programming time and improve the accuracy of your code.

The String Functions


Concept: There are several Visual Basic string functions that manipulate string data better than most other programming languages allow. The string functions allow you to strip away characters from string data and change strings in various ways.

The Visual Basic programming language supports strings using the variable-length and fixed-length strings that you've seen defined throughout the first half of this book. The string manipulation provided by Visual Basic is perhaps more powerful than any other non-BASIC programming language in widespread use today.

You've already seen the Chr$() function that converts an ASCII number to its character equivalent. (There is a related Chr() function that returns a character in the variant data type also.) The Str$() (and the related variant-returning Str() function) converts a number to a string.



Tip: Convert numbers to strings when you want to display numeric quantities inside a message box.

Suppose that the user's age were stored in a numeric variable named Age. If you wanted to display the user's age in a message box, you couldn't do so without first converting the age to a string value as follows:


MsgBox "Your age is now" & Str$(Age)

The string case-conversion functions convert their string arguments to uppercase or lowercase character strings. Table 13.4 lists these functions.

Table 13.4. The case-conversion functions.

Function Description
LCase() Returns the string argument as a variant data type that's all lowercase letters
LCase$() Returns the string argument as a string data type that's all lowercase letters
UCase() Returns the string argument as a variant data type that's all uppercase letters
UCase$() Returns the string argument as a string data type that's all uppercase letters

If the argument already contains one or more characters in the target case, the functions leave those characters alone. The remarks following these statements indicate the function return values:


lowerName = LCase("Larry") ' Returns larry

upperName = 
UCase("Smythe") ' Returns SMYTHE


Definition: A substring is a portion of a string.

Visual Basic contains three string functions that return left, center, or right portions of a string. These are the Left$(), Mid$(), and Right$() functions. All three functions are said to return a substring value. Here are the formats of these functions:



Left$(StringVal, length)

Right$(StringVal, length)

Mid$(StringVal, startVal, length)


Note: The Mid$() function is called the midstring function.

The Left$() function returns length characters from the StringVal. The StringVal might be a string constant or variable. Likewise, Right$() returns length characters from the StringVal. Mid$() returns length characters from the StringVal beginning at the startVal character.

The remarks following these statements indicate the function return values:


Title = "Something Good!"

lTitle = Left$(Title, 4) ' Some

rTitle = Right$(Title, 5) ' Good!

mTitle = Mid$(Title, 5, 8) ' thing Go

Figure 13.3 shows how Visual Basic strips these substrings from the longer string values.

Figure 13.3. Substring functions pull substrings from strings.

The Len() function returns the number of characters stored in strings. Often, you'll have to adjust control sizes to hold long strings. You can use the Len() function as a guide to calculate how wide a control must be. The following statement stores 14 in the variable named Length:

length = Len("Blue and Green")



Note: The Len() function works for numeric values as well. If you pass a numeric variable, constant, or expression to Len(), Len() returns the amount of memory needed to hold that numeric value.

The LTrim$() and RTrim$() functions trim extra spaces from the beginning or end of a string. If extra spaces don't exist, the LTrim$() and RTrim$() functions do nothing. LTrim$() returns the argument's string without any leading spaces. RTrim$() returns the argument's string without any trailing spaces. The Trim$() function handles both jobs by trimming both leading and trailing spaces from a string.

Here are the formats of the string-trimming functions:


LTrim[$](StringExpression)

RTrim[$](StringExpression)

Trim[$](StringExpression)


There are also equivalent variant functions called LTrim(), RTrim(), and Trim().

The following statements trim spaces from the beginning, end, or both sides of strings:


LStr1 = LTrim$(" Jonah") ' 
Stores Jonah

RStr2 = RTrim$("Jonah ") ' Stores Jonah

AnySt3 = Trim$(" Jonah ") ' Stores Jonah

Without the trimming functions, the spaces are copied into the target variables along with the name Jonah.

Earlier, you learned how to use Str$() to convert a number to a string. Because Str$() always converts positive numbers to strings with a leading blank (where the imaginary plus sign appears), you can combine LTrim$() with Str$() to eliminate the leading blank. The first of the following two statements stores the leading blank in st1. The second uses LTrim$() to get rid of the blank before storing the string into st2.


st1 = Str$(234) ' Stores " 234"


st2 = LTrim$(Str$(234)) ' Stores "234"

Review: The string functions manipulate strings and return values based on string arguments. As you write more powerful programs, you'll need to extract substrings and convert the case of strings in various ways to display string values on the form and in controls.

General Functions


Concept: There are a handful of general functions that don't fall into a strict numeric or string category. These general-purpose functions add power to your programming skills. This section explains how to detect data types using the Is...() and VarType() functions. You may not see a use for these functions quite yet, but familiarize yourself with them. In Lesson 8, you'll learn how to pass data back and forth between Visual Basic routines, and there are times when you'll need to know which data type was passed to you using one of the functions taught here.

Table 13.5 contains data inspection functions, often called the Is...() functions. When you store a data value in a variant variable (which can accept any data type), Table 13.5's functions returns a true or false result that indicates whether the argument can be converted to a specific data type.

Table 13.5. The Is...() data inspection functions.

Function Name Description
IsDate() Determines whether its argument can be converted to a valid date
IsEmpty() Determines whether its argument has been initialized with any value since the argument's original definition
IsNull() Determines whether its argument holds a Null value (such as an empty string)
IsNumeric() Determines whether its argument holds a value that can be converted to a valid number

The following code ensures sure that a valid string appears in the variable named ans before applying a UCase$() function:


If IsString(ans) Then

 
NewAns = UCase$(ans)

Else

 MsgBox "You didn't type a letter!"

End If

Empty variables differ from Null values and zero values. Empty variables indicate that nothing has been entered into variables. The IsNull() function checks to see whether its control argument contains a Null value.



Tip: Use IsNull() to see whether a control or field on a form contains data. Use IsEmpty() just for variables.

The VarType() function determines the data type of its argument. Table 13.6 lists the return values from the VarType() function. VarType() returns no values other than the nine listed in the table.

Table 13.6. The VarType() function's return values.

Return Description
0 Indicates that the argument is Empty
1 Indicates that the argument is Null
2 Indicates that the argument is Integer
3 Indicates that the argument is Long
4 Indicates that the argument is Single
5 Indicates that the argument is Double
6 Indicates that the argument is Currency
7 Indicates that the argument is Date
8 Indicates that the argument is String

Stop and Type: Listing 13.1 makes sure that the user entered a value into the txtAge text box control.

Review: The general-purpose functions return values that indicate data contents and data types. You can use these functions to see whether variables and controls have been initialized before calculating with those values.

Listing 13.1. Checks to make sure that the user entered a value.


1: If IsNull(txtAge.Text) Then

2: MsgBox "You didn't type anything!"

3: Else

4: MsgBox "Thanks for entering a value."

5: End If

Analysis: Line 1 ensures that the user has typed something in the control named txtAge. Subsequent code could then use the VarType() function to make sure that the user entered a value of the correct data type required by the user.

Homework



General Knowledge


  1. What is a function argument?

  2. True or false: A function's return value must match the argument list's data type.

  3. True or false: Some functions require no arguments, some one, and some several.

  4. True or false: The function's arguments must all match in data type.

  5. Why are there three integer functions?

  6. What value does Visual Basic store in Ans given the following assignment statements?
    Ans = Int(61.32)
    Ans = Int(-61.32)
    Ans = Fix(-61.32)
    Ans = Cint(421.51)

  7. True or false: Int(), CInt(), and Fix() all return the same value for positive arguments.

  8. What function performs the opposite of Chr$()?

  9. What value appears in the string variable named AList after these assignments?
    AList = UCase$("AbCdEfG")
    AList = LCase$("AbCdEfG")

  10. What would the following assignment statement store in the variant variable named Anything?
    Anything = Str$(Val("78.1"))

  11. Write the values stored in each of the following assignment statements:
    AStr = Left$("Sams", 1)
    AStr = Left$("Sams", 3)
    AStr = Right$("Sams", 1)
    AStr = Right$("Sams", 3)
    AStr = Mid$("Sams", 2, 3)

  12. True or false: Depending on the arguments, Mid$() could return the same values as Left$() and Right$().

  13. True or false: Both of the following produce the same value when used inside an expression:
    Chr$(67)
    Asc("C")

  14. What is the name of the function that converts a number to a string?


Write Code That...


  1. Suppose that you needed to display a numeric variable's value inside the prompt string of an input box. Describe how you would you concatenate such a variable to the prompt string?

  2. How could you find out the amount of memory consumed by 250 double-precision variables?

  3. Write the code that uses an input box to get a number from the user and then uses a message box to display the square root of that number.

  4. Write the code that uses two separate input boxes to ask the user for a first and last name, and then display in a message box the total number of letters in both names.

  5. Write an assignment statement that stores the ASCII value of "P" in a variable named ValAsc.


Find the Bug


  1. Rudy gets an overflow message when attempting the following assignment into the integer variable named Weight:
    Weight = CInt(32768 * Num)
    Describe the problem for Rudy.


Extra Credit


  1. Add to Listing 13.1 to make sure that the user entered an integer in the txtAge.Text control.

Write a program that stores the 256 ASCII characters (from ASCII 0 to ASCII 255) in a string array that's defined to hold 256 elements.

Previous Page Page Top TOC Next Page