It's time to learn a foreign language: Visual Basic. Until now, you created programs by placing controls on the form and setting property values for them. Visual programming like that is at the heart of Visual Basic, and visual nature
of Visual Basic is
what separates it from the more traditional text-based programming languages.
As you will see in this lesson, there is more to Visual Basic than just a pretty face! If you learn the text-based Visual Basic language in
addition to how to place and interact with controls, you can write extremely powerful applications. The Visual
Basic programming languagethe codeoften ties controls together so that your applications can analyze data and compute based on
your data.
Warning: Visual Basic is one foreign language that is really not so foreign. You will see that its vocabulary consists of simple words that you are already familiar with.
Concept:
The Visual Basic language works with all kinds of data. Before you learn how to manipulate data, you will learn how to distinguish among the various data types.
Visual Basic manipulates and analyzes seven kinds of data. Table
7.1 describes the data types that Visual Basic supports. Some data falls into more than one category. For example, a dollar amount can be considered both a currency data type and a single
data type. When you write a program, you need to decide which
data type best fits your program's data values.
Data Type | Description |
integer | Numeric values with no decimal point or fraction. integer values range from 32,768 to 32,767. |
long | Integer values with a range beyond than that of integer data values. long data values range from 2,147,483,648 to 2,147,483,647. long data values consume more memory storage than integer values, and they are less efficient. The long data type is often called long integer. |
single | Numeric values that range from 3.402823E+38 to 3.402823E+38. The single data type is often called single-precision. |
double | single numeric values that range from 1.79769313486232E+308 to 1.79769313486232E+308. The double data type is often called double-precision. |
currency | Data that holds dollar amounts from $922,337,203,685,477.5808 to $922,337,203,685,477.5807. |
string | Data that consists of 065,500 characters of alphanumeric data. Alphanumeric means that the data can be both alphabetic and numeric. string data values may also contain special characters such as ^%@. |
variant | Used for data stored in controls and for date and time values. |
The following data values can take
on the integer data type:
21
0
-9455
32766
You can also store these integer data types as long data
types, although doing so wastes storage and time unless you plan to change the values later to extremely large or small integer numbers that require the long data type.
The following data values must be stored in a long data type:
32768
-95445
492848559
The following data values can take on the single data type:
0.01
565.32
-192.3424
9543.5645
6.5440E-24
Of course, you can store these data values in double storage locations as well. Use
double data types only when you need to store extra large or small values.
The following data values take on the double data type:
-5968.5765934211133
4.532112E+92
928374.344838273567899990
What's that E Doing in the Numbers?: The E stands for exponent. Years ago, mathematicians grew weary of writing long numbers. They developed a shortcut notation called scientific notation. Visual Basic supports scientific notation. You can use scientific notation for single and double numeric data values. When you use scientific notation, you don't have to writeor type, in the case of program writingextremely long numbers.
When a single or double numeric value contains the letter E, followed by a number, that number is written in scientific notation. To convert a number written in scientific notation to its non-abbreviated form, multiply the number to the left of E by 10 raised to the power indicated by the number to the right of E. Therefore, 2.9876E+17 means to multiply 2.9876 by 10 raised to the 17th power, or 1017. 1017 is a very large numberit is 10 followed by 16 zeroes. The bottom line is that 2.9876E+17 means the same as 29876 followed by 13 zeros.
If a number uses a negative exponent, you multiply the number to left of E by 10 raised to negative power. Therefore, 2.9876E-17 means the same as 2.9876 multiplied by 10-17or 2.9876 divided by 1017which turns out to be a small number indeed.
Note: Dont consider yourself a mathematician? That's okayVisual Basic calculates all your math for you when you learn how to write programs with this book. Typically, only scientific and engineering programmers need to use scientific notation, and they feel right at home using it. Table 7.1 used scientific notation because there is no practical way of displaying the low or high range for double data values with 307 zeros in a the number.
The following data values can take on the currency data type:
123.45
0.69
63456.75
-1924.57
The currency data type can accept and track numeric values to four decimal places. However, you typically store dollar and cent values in the currency
storage locations, and these kinds of values require only two decimal places.
Note: Visual Basic uses the Windows International settingsfound in the Control Panel if you want to take the time to lookto track values such as dates, times, and currency. Therefore, if you have Windows set up for a country, such as France, that uses a comma instead of the decimal point as it is used in America, Visual Basic will support the comma when it displays your values.
Never use a currency data value along with a dollar sign. In other words, the following cannot be a currency value even though it looks
like one:
$5,234.56
Visual Basic does not want you to use a dollar sign or commas in numeric data of any kindunless, of course, your country uses the comma for the fractional portion of numbers. If
your data contains anything other than numbers, a plus sign, a minus
sign, or an exponent, Visual Basic cannot treat the data as if it were numeric; therefore, it cannot perform mathematical calculations with the data. Instead, Visual Basic treats
the data as string data.
The following data values take on the string data type:
"London Bridge"
"1932 Sycamore Street"
"^%#@#$%3939$%^&^&"
Notice the quotation marks around the three string values. string values require the quotation marks, which tell Visual Basic where the string begins and ends. If you wanted to embed
spaces at the beginning or end of a string, you indicate those spaces
by including them inside the quotation marks. For example, here are three different strings, each with a different set of embedded spaces: " house", "house ",
" house ". You cannot embed quotation marks directly inside a
string; Visual Basic thinks the string ends as soon as it comes to the second quotation mark, even if it is not the actual end of the string.
Note: You just caught me in a lie. Actually, there is a way to embed quotation marks in string data, but doing so is messy and requires the use of a built-in function that you will learn about in Lesson 7.
The following data values can take on the variant data type:
"^%#@#$%3939$%^&^&"
123.45
4.532112E+92
21
03-Mar-1996
Do these values look familiar? The variant data type can hold data of any other data type. Think about the kind of
data stored in label controls. You often want to display numbers, dollar amounts, times, and dates in labels on a form. You
can always store variant data in these controls. The data that comes from these controls is also variant.
Visual Basic offers you several ways to convert data from one type to another. For example, "34" is a string value because of the quotation marks. You cannot perform math on string data. However, if you store a string that contains a
valid
number and decide that you need to perform math on the value, Visual Basic provides a built-in data-conversion routine that enables you to convert the string to a number so that you can do math with its value. The data type differences exist so
that you
can adequately store and describe certain data values.
Note: Visual Basic uses the variant data type for date and time values, as you will learn in Lesson 7, "Functions and Dates."
Definition: A constant is a data value that does not change.
The data values that you saw in this section are all constants. A constant does not change. For example, the number 7 is always 7, and never means anything except 7. There are times when you must
explicitly state exactly what kind of constant a data
value is so that Visual Basic works properly with the data. For example, 7 is a constant, and neither you nor Visual Basic can tell whether 7 should be stored in an integer or a long integer data
location.
variant data is the only kind of data that Visual Basic changes, when needed, to suit the situation at hand. In other words, if you store a long integer value in a variant data area, you can perform math with the variant value. If
you store a string in
a variant data area, you'll be able to perform string operations on the data.
If you run into a situation where a particular data type constant is required, you dont have to use of the default variant data type.
You can explicitly state what data type a certain constant is. By adding one of the data type suffix characters
listed in Table 7.2 to your constant data, you supply the data type when you use the constant.
Suffix | Data Type | Example |
& | long | 14& |
! | single | 14! |
# | double | 14# |
@ | currency | 14@ |
You dont need the suffix characters very often. Most of the time, you can get by with assigning constants to controls and data areas without needing to add a suffix character to the end of the name.
Remember that Visual Basic assumes the
data constant is a variant data type unless you use a suffix character to override that assumption. Because variant data can convert to any other data type, you almost always can use the default variant data
type.
Your programs are made up of the data that changes and constant data, which remains the same. Many times you must specify constant values, such as the number of months in a year, the number of hours in a day, or a company name. Other
times, you work
with values that change over time, such as an employee's salary or an inventory valuation. The next section discusses how to set up and use data values that change over time.
Tip: Is your head spinning yet? If you have never programmed beforeand this book assumes that you never havethis talk about data types has jumped right into hard material that seems technical and frustrating. You really haven't seen a reason to use these data types yet. The next section helps explain why these data types are so important. So don't give up just yetnot that you were going to, but I just wanted to be sure!
Review: All Visual Basic data falls in one of seven data types. The kind of data you work with and the range of the data values that you use determine which data type a value
will take. The various data types
enable you to categorize data and to perform specific functions on certain kinds of data.
Concept: As you know, your computer has memory. You can store data values in memory locations that your Visual Basic program then operates on. When you define
variables, you reserve places in memory for data
variables, name those variables, and decide what data type those variables will hold.
Definition: A variable is a named storage location that holds data that changes.
Throughout a program, you need to store data in memory locations while you compute with that data. Those memory locations are called
variables. A variable, unlike a constant, can change. In other words, you can store a number in a variable early
in the program and then change that number later in the program. Some variables might not changesuch as when the application
does not need the variable to changebut often the contents of variables do change.
A variable is like a box in memory that holds a data value. The two characteristics of variables are
The following sections explain how you can request variables from Visual Basic so that you have places to put data values that you need to store.
Definition: To define a variable means to create and name a variable.
A program can have as many variables as you need it to have. Before you can use a variable, you must request that Visual Basic create the variable by defining
the variable first. When you define a variable, you tell Visual Basic these two things:
Once you define a variable, that variable always
retains its original data type. Therefore, a single-precision variable can hold only single-precision values. If you stored an integer in a single-precision variable, Visual Basic would convert the
integer to a single-precision number before it
stored the number in the variable. Such conversions are common, and they typically do not cause many problems.
The Dim statement defines variables. Using Dim, you tell Visual Basic
Dimshort for dimensionis a Visual Basic statement that you write in an applications Code window. Whenever you learn a new
statement, you need to learn the format for that statement. Here is the format of the Dim statement:
Dim VarName AS DataType
VarName is a name that you supply. When Visual Basic
executes the Dim statement at runtime, it creates a variable in memory and assigns it the name you give in the VarName location of the statement. DataType is one of the seven
Visual Basic data types that you learned about in Table 7.1.
Tip: Think of a variable as an internal label control that the user cannot see. The variable has a name and holds data just like the label control has a Name property and holds a caption. Variables are more specific than controls, however, because of their data type requirements.
Variable names must follow the same naming rules as controls. In Unit 4, you learned the naming conventions for a controls Name propertyfor example, the name must be from 1 to 40 characters long, cannot be a reserved
word, and so on.
Always use a Dim statement to define
variables before you use variables. If the Options Environment Require Variable Definition option is set to Yesas it is by defaultVisual Basic will issue an error message whenever you use a variable that
you have not defined. This option
prevents you from inadvertently misspelling variable names and helps you avoid errors in your program.
Suppose that you give a partial program to another Visual Basic programmer to work on. If you want to require that all variables be
defined but are unsure of the other programmer's Options Environment Require Variable Definition setting, select
(general) from the Code window's Object dropdown list and add the following special statement:
Option Explicit
No matter how the Options Environment setting is set, the programmer cannot slip variables into your program without defining them properly in Dim statements. Again, requiring variable definitions helps
eliminate bugs down the road, so you are wise to
get in the habit of putting Option Explicit in the (general) section of every programs Code window.
The following statement defines a variable named ProductTotal:
Dim ProductTotal As Currency
From the Dim statement, you know that the variable holds currency data and that its name is ProductTotal. All Visual Basic commands and built-in routines require an initial capital
letter. Although you don't have to name your variables with an initial
capital letter, most Visual Basic programmers do for the sake of consistency. Additional caps help distinguish individual words inside a name. (Remember that you cannot use spaces
in the name of variable.)
Note: The Static and Global statements also define variables, as you will see in Lessons 6 and 8.
The following statements define integer, single-precision, and double-precision variables:
Dim Length As Integer Dim Price As Single Dim Structure As Double
Warning: Except for rare occasions that you will learn about in Lesson 8, "Modular Programming," never define two variables with the same name. Visual Basic wont know which one you are referring to when you try to use one of them.
Definition: A variable-length string holds strings of any length.
If you want to write a program that stores the user's text box entry for the first name, you would define a string like this:
Dim FirstName As String
You can get fancy when you define strings. This FirstName string can hold any string from 0 to 65,500 characters long. You will learn in the next section how to store data in a string. FirstName can hold data of
virtually any size. You could store a
small string in FirstNamesuch as "Joe"and then store a longer string in FirstNamesuch as "Mercedes". FirstName is a variable-length string.
Definition: A fixed-length string holds strings of a preset maximum fixed size.
Sometimes you want to limit the amount of text that a string
holds. For example, you might need to define a string variable to hold a name that you read from the disk file. Later, you will display the contents of the string in a label on the form. The
form's label has a fixed length, howeverassuming that
the AutoSize property is set to True. Therefore, you want to keep the string variable to a reasonable length. The following Dim statement demonstrates how you can add the * StringLength
option when you want to define fixed-length strings:
Dim Title As String * 20
Title is the name of a string variable that can hold a string from 0 to 20 characters long. If the program attempts to store a string value that is longer than 20
characters in Title, Visual Basic truncates the string and stores only the first 20
characters.
Here's a shortcut: You can omit the As Variant descriptor when you define variant variables. This Dim statement:
Dim Value As Variant
does exactly the same thing as
Dim Value
A good rule of thumb is to make your code as explicit as possible. In other words, As Variant
requires extra typing at the keyboard, but using the As Variant makes your request for a variant variable clearer. When you later maintain the program, you
will know that you meant to define a variant variable and that you did not accidentally
omit a different data type.
As you will see throughout this book, you use variables to hold intermediate mathematical results, as well as data values typed by the user in controls such as text boxes. Variables work well with the controls on
the form. So far, you have learned how
to define variables but not store data in them. The next section explains how to store and retrieve values from the variables that you define.
Warning: If you begin calling a variable one name, you must stay with that name for the entire program. Sale is not the same variable name as Sales. If you define a variable using a name and later change only the case of certain letters, Visual Basic will convert the original case to the new case. In other words, if you define a variable with the name Profit and use that name for a while in the program, but later in the program you call the variable PROFIT, Visual Basic changes all previous occurrences of Profit to PROFIT.
Visual Basic supports a shortcut when you need to define several variables. Instead of listing each variable definition on separate lines like
this:
Dim A As Integer Dim B As Double Dim C As Integer Dim D As String Dim E As String
you can combine the variables of the same data type on one line. For example,
Dim A, C As Integer Dim B As Double Dim D, E As String
Some programmers even code all variable definitions on the same line. As you can see, though, too many variable definitions makes Dim hard to manage. For
example,
Dim A, C As Integer, B As Double, Dim D, E As String
Reducing Dim with Variable Suffix Characters: There is a set of suffix characters for variable names that you can use to specify a variable's data type without having to define the variable first. Table 7.2 listed the suffix characters for constant values. Variables use the more complete version shown here:
Suffix Data Type Example
% integer Age% & long Amount& ! single Distance! # double KelvinTemp# @ currency Pay@ $ string LastName$
The statement Option Explicit cannot appear in the (general) section of the Code window because the suffix characters are not enough to define variables.
The variable LastName$ is a string variable, and Visual Basic knows that the variable is a string variable even if no Dim statement defines the variable as a string. You wont use the variable suffixes much because you will write clearer programs if you use Dim. Nevertheless, you might run into code written by others that uses the suffix characters on variables, and you should be aware of what the suffix characters mean.
Definition: A null string is a zero-length empty string that is often represented as "".
When you first define variables, Visual Basic stores zeroes in the numeric variables and null strings in the string variables. Use the assignment statement when you
want to put other data values into variables. Variables hold data of specific
data types, and many lines inside a Visual Basic program's Code window consist of assignment statements that assign data to variables. Here is the format of the assignment
statement:
[Let]VarName = Expression
The Let command name is optional; it is rarely used these days. The VarName is a variable name that you have defined using the Dim statement.
Expression can be a constant, another variable, or a mathematical expression.
Suppose that you need to store a minimum age value of 18 in an integer variable named MinAge. The following assignment statements do that:
Let MinAge = 18
and
MinAge = 18
Note: The rest of this book omits Let from assignment statements because the word is superfluous.
To store a temperature in a single-precision variable named TodayTemp, you could do this:
TodayTemp = 42.1
The data type of Expression must match the data type of the variable to which you are assigning. In other words, the following statement is invalid. It would produce an error in Visual Basic
programs if you tried to use it.
TodayTemp = "Forty-Two point One"
If TodayTemp were a single-precision variable, you could not assign a string to it. However, Visual Basic often
makes a quick conversion for you when the conversion is trivial. For example, it is possible to perform the following assignment even if you
have defined Measure to be a double-precision variable:
measurement = 921.23
At first glance, it appears that 921.23 is a single-precision number because of its size. 921.23 is actually a variant data value. Recall that Visual Basic assumes all data constants are variant unless you explicitly add a
suffix character to the
constant to make the constant a different data type. Visual Basic can easily and safely convert the variant value to double-precision. That's just what Visual Basic does, so the assignment works fine.
In addition to
constants, you can assign other variables to variables. Consider the following code:
Dim Sales As Single, NewSales As Single Sales = 3945.42 NewSales = Sales
When the third statement finishes,
both Sales and NewSales have the value 3945.42.
Feel free to assign variables to controls and controls to variables. Suppose, for example, that the user types the value 18.34 in a text box's Text property. If the text box's Name property is
txtFactor, the following statement stores the value of the
text box in a variable named FactorVal:
FactorVal = txtFactor.Text
Suppose that you defined Title to be a string variable with a
fixed length of 10, but a user types Mondays Always Feel Blue in a text box's Text property that you want to assign to Title. Visual Basic stores only the first ten characters of the control
to Title and truncates the rest of the title. Therefore,
Title holds only the string "Mondays Al".
Stop & Type: This is the first of several program code reviews that you will find throughout the rest of the book. Listing 7.1 contains a
short event procedure that assigns a new command button caption.
Review: You can instantly make data appear on the form by assigning the Text property of text boxes or the Caption property of labels
and command buttons. Suppose you put a command button named cmdJoke on a
form. The event procedure shown in Listing 7.1 changes the command button's caption when the user clicks the command button.
Listing 7.1. An
event procedure that assigns a new command button caption.
1: Sub cmdJoke_Click () 2: cmdJoke.Caption = "Bird Dogs Fly" 3: End Sub
Warning: Throughout this book, you will often see code listings with numbers down the left side. The numbers are used to refer to individual lines. Don't actually type the numbers or the colons that follow them when you enter the program code.
Analysis: No matter what the command button's Caption property is set to at the start of the program, when the user
clicks the command button, this event procedure executes and the command button's caption
changes to Bird Dogs Fly (line 2).
Tip: You will see a more comprehensive program that assigns data values to and from form controls in this lesson's project.
Provided that you have added the CONSTANT.TXT file to AUTOLOAD.MAK, you can assign the named constants in
CONSTANT.TXT to controls inside event procedures. The following assignment statement adds a single line border around the label named lblSinger:
lblSinger.BorderStyle = FIXED_SINGLE
Of course,
you must know the names of the named constants inside CONSTANT.TXT before you can assign them. Throughout this book, I will point out when you can use named constants for setting properties.
Note: When you are not using CONSTANT.TXT, assign only the number when a control's property can accept a limited range of values. For example, the possible values that you can select for a label's BorderStyle in the Properties window are 0-None and 1-Fixed Single. To assign either border style directly without using a named constant, assign just 0 or 1. Don't spell out the entire property. For example,
lblSinger.BorderStyle = 1
Review: Using the assignment statement, you can assign constants, named constants, control values, and variables to other variables and controls. The assignment statement
requires that your variables first be
defined with Dim if your program's (general) procedure contains an Option Explicit 1 statement, as I have suggested.
Concept: Data values and controls are not the only kinds of assignments that you can make. With the Visual Basic math operators,
you can calculate and assign expression results to variables when you code
assignment statements that contain expressions.
Definition: An operator is a word or symbol that does math and data manipulation.
It is easy to make Visual Basic do your math. Table 7.3 describes Visual Basic's primary math operators. There are other operators, but the ones in
Table 7.3 will suffice for most of the programs that you write. Look over the operators. You are already
familiar with most of them because they look and act just like their real-world counterparts.
Operator | Example | Description |
+ | Net + Disc | Adds two values |
- | Price - 4.00 | Subtracts one value from another value |
* | Total * Fact | Multiplies two values |
/ | Tax / Adjust | Divides one value by another value |
^ | Adjust ^ 3 | Raises a value to a power |
& or + | Name1 & Name2 | Concatenates two strings |
Suppose that you wanted to store the difference between the annual sales (stored in a variable named
AnnualSales) and cost of sales (stored in a variable named CostOfSales) in a variable named NetSales. Assuming that all three variables have
been defined and initialized, the following assignment statement computes the correct value for NetSales:
NetSales = AnnualSales - CostOfSales
This assignment tells Visual Basic to compute the value of the expression and to store the result in the variable named NetSales. Of course, you can store
the results of this expression in Caption or Text properties, too.
If you want to raise a value by a powerwhich means to multiply the value by itself a certain number of timesyou can do so. The following code assigns 10000 to
Value because ten raised to the fourth power10x10x10x10is 10,000:
Years = 4 Value = 10 ^ Years
No matter how complex the expression is, Visual Basic computes the entire result before it
stores that result in the variable at the left of the equals sign. The following assignment statement, for example, is rather lengthy, but Visual Basic computes
the result and stores the value in the variable named Ans:
Ans = 8 * Factor - Pi + 12 * MonthlyAmts
Combining expressions often produces unintended results because Visual Basic computes mathematical results in a predetermined order. Visual Basic always calculates
exponentiation first if one or more ^ operators appear in the expression. Visual Basic
then computes all multiplication and division before any addition and subtraction.
Visual Basic assigns 13 to Result in the following assignment:
Result = 3 + 5 * 2
At first, you might think that Visual Basic would assign 16 to Result because 3 + 5 is 8 and 8 * 2 is 16. However, the rules state that Visual Basic always computes
multiplicationand division if division exists in the expressionbefore
addition. Therefore, Visual Basic first computes the value of 5 * 2, or 10, and next adds 3 to 10 to get 13. Only then does it assign the 13 to Result.
If
both multiplication and division appear in the same expression, Visual Basic calculates the intermediate results from left to right. For example, Visual Basic assigns 20 to the following expression:
Result = 8 / 2 + 4 + 3 * 4
Figure 7.1 shows how Visual Basic computes this expression. Visual Basic computes the division first because the division appears to the left of the multiplication. If the multiplication appeared to the left of the
division, Visual Basic would have
multiplied first. After Visual Basic calculates the intermediate answers for the division and the multiplication, it performs the addition and stores the final answer of 20 in Result.
Figure 7.1. Visual Basic computes expressions in a predetermined order.
Note: The order of computation has many names. Programmers usually use one of these terms: order of operators, operator precedence, or math hierarchy.
It is possible to override the operator precedence by using parentheses. Visual
Basic always computes the values inside any pair of parentheses before anything else in the expression, even if it means ignoring operator precedence. The following
assignment statement stores 16 in Result because the parentheses force Visual Basic
to compute the addition before the multiplication:
Result = (3 + 5) * 2
Tip: Appendix B contains the complete Visual Basic operator precedence table. The table contains several operators that you have yet to learn about, so you might not understand the full table at this time.
The
following expression stores the fifth root of 125 in the variable named root5:
root5 = 125 ^ (1/5)
As you can see from this expression, Visual Basic supports fractional exponents.
Definition: Concatenation means the joining together of two or more strings.
One of Visual Basic's primary operators has
nothing to do with math. The concatenation operator joins one string to the end of another. Suppose that the user entered his first name in a label control named lblFirst and his last name in a label control
named lblLast. The following concatenation
expression stores the full name in the string variable named FullName:
FullName = lblFirst & lblLast
There is a problem here, though, that might not be readily apparentthere is no
space between the two names. The & operator does not automatically insert a space because you dont always want spaces inserted when you concatenate two
strings. Therefore, you might have to concatenate a third string between the other two,
as in
FullName = lblFirst & " " & lblLast
Visual Basic actually supports a synonym operator, the plus sign, for concatenation. In other words, the following assignment
statement is identical to the previous one:
FullName = lblFirst + " " + lblLast
Even Microsoft, the maker of Visual Basic, recommends that you use & for string concatenation and
reserve + for mathematical numeric additions. Using the same operator for two different kinds of operations can lead to confusion.
Review: The math operators enable you to perform all kinds of
calculations and assignments. Visual Basic means never having to use a calculator again! When you use expressions, however, remember operator
precedence. When in doubt, use parentheses to indicate exactly which operations in an expression you want
Visual Basic to calculate first.
Concept: Visual Basic treats all data stored in controls on the form as variant values. There is a quirk in Visual Basic that makes Visual Basic think these controls are strings when you want to add two control
values together. The Val() function makes sure that Visual Basic treats control values as numbers when you need numbers for expressions.
Figure 7.2 shows a simple form with two text boxes and a command button. As soon as the user types last
year's sales into a text box named txtLast and this year's sales into a text box named txtThis, the command button triggers a Click event procedure
that does the following:
lblAvg = (txtLast.Text + txtThis.Text) / 2
Figure 7.2. Computes the average sales value for two years.
Despite the fact that everything is correct about this expression, Visual Basic does not store the
average of the two text boxes in the lblAvg label. Visual Basic incorrectly thinks that you want to concatenate the two text box values instead of adding
them.
Note: See the problems that can occur when a language uses the same operator, +, for two different purposes!
Instead of using this relatively simple expression, you must add a little mess by using the
Val() function. The word Val() looks like the name of an event procedure because of the parentheses. However, Visual Basic has several built-in routines called
functions. Function names end with parentheses. You will learn all about Visual
Basic functions in Lesson 7. For now, just use the functionsthey're easyand dont worry about how they work.
Here's how you use Val(): Put a stringor something that Visual Basic might think is a string, such as a
controlinside the parentheses. As long as the parenthetical value can be interpreted as a number, even if the value is stored as a
string, Visual Basic converts the value to a number temporarily so that you can calculate a mathematical result.
The previous assignment requires that you use Val() twice. For example, instead of
lblAvg = (txtLast.Text + txtThis.Text) / 2
you must code
lblAvg = (Val(txtLast.Text) + Val(txtThis.Text)) / 2
Val() ensures that Visual Basic treats the text boxes as numeric quantities and not as strings.
By the way, if the user does not enter numbers in both text boxes, Visual Basic uses
zero for the converted number if no numeric digits appear in the text boxes. If any number or set of digits appears in the text boxes, Val() uses those digits for the
converted number, often producing funny results. For example, if txtLast.Text
contains 18 years old (why the user would type that for a sales figure is beyond me!), Val() strips off the 18 and uses 18 for the numeric value in the average
calculation.
Note: You can find this simple sales averaging program under the name SALAVG.MAK on the disk that comes with this book. The program is extremely simple. It does not format the average to dollars and cents, so you might have more or fewer than two decimal places. Nevertheless, you can load and study the program's cmdAvg_Click() procedure to get a feel for the calculation being performed and for how Val() helps the calculation.
Review: When you calculate using the form's data, you might have to convert control values to numbers temporarily by using Val() before you use the values in numeric
expressions. The controls retain their
variant data types except for the locations where Val() converts the label data types to numbers.
Add a third label to the SALAVG.MAK averaging program shown in Figure 7.2 so that the program averages three sales values.