Visual Basic in 12 Easy Lessons vel08.htm

Previous Page TOC Next Page



Lesson 4, Unit 8


Data Comparisons



What You'll Learn


Computers cannot think on their own, but with your help they can be taught to make decisions based on values contained in controls and variables. Visual Basic’s decision-making capability enables it to calculate sales figures based on certain conditions, to print exception reports, and to check user responses by means of the form’s controls.

You have learned only a few statements so far:

In addition, you know about the fundamental math operators. In this unit, you will learn some new programming statements and operators that you can use along with the ones you already know to write programs that make data-based decisions.

The Relational Operators


Concept: Visual Basic supports the use of six operators that produce true or false results based on data values. Once you learn the relational operators, you can combine them operators with the If statement to add power to your programs.



Definition: Relational operators compare data values to one another.

Table 8.1 describes the six relational operators that Visual Basic supports. You use the relational operators to compare data values. They are easy to use. If you take any two numbers, one number is always be greater than, equal to, or less than the other.



Note: The mathematical operators that you learned in the previous unit produced numeric answers. The relational operators produce only true and false answers. In other words, one data value is either more than another—a true result—or the data value is not more than the other—a false result.


Table 8.1. The relational operators.

Operator Usage Description
> Sales > Goal The greater than operator. Returns true if the value on the left side of > is numerically or alphabetically greater than the value on the right. Otherwise, false.
< Pay < 2000.00 The less than operator. Returns true if the value on the left side of < is numerically or alphabetically less than the value on the right. Otherwise, false.
= Age = Limit The equal to operator (sometimes called the equal operator). Returns true if the values on both sides of = are equal to each other. Otherwise, false.
>= FirstName >= "Mike" The greater than or equal to operator. Returns true if the value on the left side of >= is numerically or alphabetically greater than or equal to the value on the right. Otherwise, false.
<= Num <= lblAmt.Caption The less than or equal to operator. Returns true if the value on the left side of <= is numerically or alphabetically less than or equal to the value on the right. Otherwise, false.
<> txtAns.Text <> "Yes" The not equal to operator. Returns true if the value on the left side of <> is numerically or alphabetically unequal to the value on the right. Otherwise, false.


Definition: The ASCII table is a list of characters with corresponding numeric representations.

All the relational operators work on both numeric and alphabetic values. You can compare any kind of number against another number, or any kind of string against another string. When you compare strings, Visual Basic uses the ASCII table, included in Appendix A, to determine how to compare the characters. For example, the ASCII table says that the uppercase letter A—whose ASCII numeric value is 65—is less than the uppercase letter B—whose ASCII numeric value is 66. Notice that all uppercase letters are less than lowercase letters. Therefore, the abbreviation ST is less than St.



Tip: Pronounce ASCII as ask-ee.

To understand how relational operators work, you must understand how to use their true or false results. The If statement, introduced in the next section, explains how you can take use true and false results to make decisions in your program. Before you read the next section, make sure that you understand how these operators compare values. For a quick self-test, make sure that you understand the Result column of Table 8.2 before you go any further.

Table 8.2. Relational results.

Relation Result
10 > 5 True
5 > 10 False
5 < 10 True
"Apple" <= "Orange" True
"Mac Donald" < "Mc Donald" True
0 >= 0 True
0 <= 0 True
1 <> 2 True
2 >= 3 False


Keep Each Side a Consistent Data Type: The expressions on both sides of a relational operator must have the same data type or at least compatible data types. In other words, you cannot compare a string to a numeric data type. If you try, you will get a Type mismatch error because the data types don't match.
You can compare any numeric data type against any other numeric data type most of the time. In other words, you can test whether a single-precision value is less than or greater than an integer value. Be careful, however, when you compare non-integer numeric data for equality. Precision numbers are difficult to represent internally. For example, if you assigned 8.3221 to a single-precision variable and assigned 8.3221 to another single-precision variable, Visual Basic might return a false result if you compare the values for equality. Internally, one of the variables might actually hold 8.322100001 because of rounding errors that occur in normally insignificant decimal places. You can safely compare two currency values for equality, however, because Visual Basic maintains their accuracy to two decimal places.




Note: The relational operators are sometimes called the conditional operators because they test conditions that are either true or false.

Review: The relational operators compare values against one another. You can compare for equality, inequality, and size differences. The relational operators work for both string data and numeric data. By themselves, the relational operators would not be worth much. However, you can use them to compare data by using the If statement, which you learn about in the next section.

The If Makes Decisions


Concept: The If statement uses the relational operators to test data values. It perform one of two possible code actions, depending on the result of the test. In the previous unit, you saw how Visual Basic executes the Dim and assignment statements in the order in which you type them in the program. With If statements, Visual Basic tests whether to execute blocks of code. In other words, an If statement uses the relational operators to test data and might execute one or more lines of subsequent code, depending on the results of the test.

The If statement makes decisions. If a relational test is true, the body of the If statement executes. In fact, the previous sentence is almost identical to Visual Basic's If statement. Here is one format of If:


If relationalTest Then

 One or 
more Visual Basic statements

End If

The End If statement informs Visual Basic where the body of the If statement ends. Suppose that the user enters a sales figure into a text box control named txtSales. The following If statement computes a bonus amount based on the sales:


If (txtSales.Text > 5000.00) Then

 Bonus = Val(txtSales.Text) * .12

End If

Remember that Visual Basic stores zero in all variables that you don't first initialize. Therefore, Bonus has a zero before the If statement executes. Once the If executes, the code changes the Bonus variable only if the value of the txtSales.Text property is more than 5000.00. The Val() function converts the text box's variant data to a numeric value for the computation. In a way, the If reads like this:

If the sales are more than $5,000.00, then compute a bonus based on that sales value.

The body of an If can have more than one statement. The following If calculates a bonus, the cost of sales, and a reorder amount based on the value of the txtSales text box entry:


If (txtSales.Text > 5000.00) Then

 Bonus = Val(txtSales.Text) * .12

 CostOfSales = Val(txtSales.Text) * 
.41

 ReorderCost = Val(txtSales.Text) * .24

End If

The three statements that make up the body of the If execute only if the condition txtSales.Text > 5000.00 is true. Suppose that this code contains another assignment statement immediately after End If. That assignment statement is outside the body of the If,so the true or false result of the condition affects only the body of the If. Therefore, the tax computation in the following routine executes regardless of whether the sales are more than or less than $5,000.00:


If (txtSales.Text > 5000.00) Then

 Bonus = Val(txtSales.Text) * .12

 CostOfSales = Val(txtSales.Text) * .41

 ReorderCost = Val(txtSales.Text) * .24

End If

Tax = .12 * 
Val(txtSales.Text)


Tip: The parentheses are not required around the relational test in an If statement, but they help separate the test from the rest of the code.

Can you see how the program makes decisions using If? The body of the If executes only if the relational test is true. Otherwise, the rest of the program continues as usual.

There is a shortcut form of If that you might run across. The single-line If statement has a format that looks like this:


If relationalTest Then VBStatement

The single-line If does not require an End If statement because relational test and the body of the If reside on the same line. Single-line If statements do not provide for easy program maintenance. If you decide that you want to add to the body of the If, you must convert the single-line If to a multiple-line If,and you might forget to then add End If. Therefore, even if the body of an If statement takes only one line, code the If as a multiple-line If-End If statement.

Review: The If statement determines whether code executes. The If checks the true or false condition of the relational test. If the data relationally tests true, Visual Basic executes the body of the If. If the data relationally tests false, Visual Basic skips over the body of the If statement. No matter what happens, the code that follows the End If statement executes as usual.

Handling False Conditions


Concept: Whereas If executes code based on the relational test's true condition, the Else statement executes code based on the relational test's false condition. Else is actually part of the If statement. This section explains the full If-Else statement. It shows you how you can execute one section of code or another, depending on the relational test.

The Else statement, part of an extended If statement, specifies the code that executes if the relational test is false. Here is the complete format of the If statement with Else:


If relationalTest Then

 One or more Visual Basic statements

Else

 One or more Visual Basic 
statements

End If

Typically, programmers call this full-blown If statement the If-Else statement. The If-Else statement is sometimes called a mutually exclusive statement. The term mutually exclusive simply means that one set or of code or the other executes, but not both. The If-Else statement contains two sets of code—that is, two bodies of one or more Visual Basic statements—and only one set executes, depending on the result of the If. An If statement is either true or false. Therefore, either the first or the second body of code in an If-Else executes.

Stop & Type: Suppose that a salesman receives a bonus if sales are high (over $5,000.00) or suffers a pay cut if sales are low (below $5,000.00). The If-Else in Listing 8.1 contains the code necessary to reward or punish the salesman. The code body of the If computes the bonus as done in the previous section. The code body of the Else subtracts $25 from the saleman’s pay, which is stored in the variable named PayAmt, if the sales quota is not met.

Listing 8.1 contains a code fragment—sometimes called a code snippet—because the listing does not show variable definitions or any previous code that initialized PayAmt with the salesman’s pay. Listing 8.1 contains only the If-Else code needed to reward or punish the salesman’s effort.

Review: The If handles the true result of a conditional test and the Else handles the false result. By using an If-Else, you can increase the power of Visual Basic’s data-testing and decision-making capabilities.

Listing 8.1. Determining a sales bonus or penalty.


1: If (Val(txtSales.Text) > 5000.00) Then

2: Bonus = .05 * Val(txtSales.Text)

3: Else

4: PayAmt = PayAmt - 25.00

5: End If

6: Taxes = PayAmt * .42

Analysis: Notice that line 6 computes a tax amount. No matter what the outcome of the If-Else’s relational test is, line 6 always executes. Line 6 is not part of either the If body or the Else body of code.

Line 1 tests whether the salesman's sales value—stored in the text box named txtSales—is more than $5,000.00. If the relational test is true, line 2 computes a bonus. If the test is false, Else executes (line 4).

As Figure 8.1 illustrates, either the If's body of code executes or the Else's body of code executes, but never both. Visual Basic decides in line 1 which assignment to make.

Figure 8.1. Either the If body or the Else body executes, but not both.

Line 4 introduces an assignment statement that might surprise you at first. Line 4 appears to make the statement that the pay is equal to the pay minus 25. You know that nothing can be equal to itself minus 25. In math, the equal sign acts as a balance for the two sides of the equation. In Visual Basic, however, when the equal sign is not used inside an If's relational test, it is an assignment it that takes everything to the right of the equal sign and stores that value in the variable to the left of the equal sign. Line 4 first subtracts the 25 from PayAmt and then assigns that result back to PayAmt. In effect, it lowers the value of PayAmt by 25.



Note: When a variable appears on both sides of an assignment's equal sign, the variable is being updated in some way.


Logical Operators


Concept: Three additional operators, And, Or, and Not, look more like commands than operators. And, Or, and Not are called logical operators. Logical operators enable you to add to the power of relational operators by extending the tests that your If statements can make. They enable you to combine two or more relational tests.

Table 8.3 describes the logical operators, which work just like their spoken counterparts.

Table 8.3. The logical operators.

Operator Usage Description
And If (A > B) And (C < D) Returns true if both sides of the And are true. Therefore, A must be greater than B and C must be less than D. Otherwise, the expression returns a false result.
Or If (A > B) Or (C < D) Returns true if either side of the Or is true. Therefore, A must be greater than B or C must be less than D. If both sides of the Or are false, the entire expression returns a false result.
Not If Not(Ans = "Yes") Produces the opposite true or false result. Therefore, if Ans holds "Yes", the Not turns the true result to false.

As you can see from Table 8.3, the And and Or logical operators enable you to combine more than one relational test in a single If statement. The Not negates a relational test. You can often turn a Not condition around. Not can produce difficult relational tests, and you should use it cautiously. The last If in Table 8.3, for instance, could easily be changed to If (Ans <> "Yes") to eliminate the Not.

Your code often must perform an assignment, print a message, or display a label if two or more conditions are true. The logical operators make the combined condition easy to code. Suppose that you want to reward the salesman if sales total more than $5,000 and if the he sells more than 10,000 units of a particular product. Without And, you have to embed an If statement in the body of another If statement. For example,


If (Sales > 5000.00) Then

 If (UnitsSold > 10000) Then

 Bonus = 50.00

 End If

End If

Here is the same code rewritten as single If. It is easier to read and to change later if you need to update the program.


If (Sales > 5000.00) And (UnitsSold > 10000) Then

 Bonus = 50.00

End If

How can you rewrite this If to pay the bonus if the salesperson sells either more than $5,000 in sales or if he sells more than 10,000 units? Here is the code:


If (Sales > 5000.00) Or (UnitsSold > 10000) Then

 
Bonus = 50.00

End If

Stop and Type: Listing 8.2 contains an If-Else that tests data from two divisions of a company and calculates values from the data.

Review: The logical operators enable you to combine two or more conditional tests. Without logical operators, you must code a longer series of nested If statements.

Listing 8.2. Calculating sales figures for a company’s divisions.


1: If (DivNum = 3) Or (DivNum = 4) Then

2: DivTotal = DivSales3 + DivSales4

3: GrandDivCosts = (DivCost3 * 1.2) + (DivCost4 * 1.4)

4: Else

5: 
DovTotal = DivSales1 + DivSales2

6: GrandDivCosts = (DivCost1 * 1.1) + (DivCost5 * 1.9)

7: End If

Analysis: Assume that the users of the code in Listing 8.2 own a company with four divisions. The east coast divisions are numbered 3 and 4, and the west coast divisions are numbered 1 and 2. Listing 8.2 calculates aggregate sales and costs totals for one of the coasts, depending on the DivNum value. You must assume that all the variables have been defined and initialized with proper values.

If DivNum contains either a 3 or a 4, the user is requesting figures for the east coast, and the code in lines 2–3 executes to produce an east coast pair of values. If DivNum does not contain a 3 or a 4, the program assumes that DivNum contains a 1 or a 2,and the west coast pair of values is calculated in lines 5–6.

Multiple Choice with Select Case


Concept: The If statement is great for data comparisons in cases where one or two relational tests must be made. When you must test against more than two conditions, however, the If becomes difficult to maintain. The logical operators help in only certain kinds of conditions. At other times, you must nest several If-Else statements inside one other.

Consider the If statement shown in Listing 8.3. Although the logic of the If statement is simple, the coding is extremely difficult to follow.

Listing 8.3. Nested If-Else statements get complex quickly.


If (Age = 5) Then

 lblTitle.Text = "Kindergarten"

Else

 If (Age = 6) Then

 lblTitle.Text = "1st Grade"

 Else

 If (Age 7) Then

 lblTitle.Text = "2nd Grade"

 Else

 
If (Age = 8) Then

 lblTitle.Text = "3rd Grade"

 Else

 If (Age = 9) Then

 lblTitle.Text = "4th Grade"

 Else

 If (Age = 10) Then

 lblTitle.Text = "5th Grade"

 Else

 If (Age = 11) Then

 lblTitle.Text = "6th 
Grade"

 Else

 lblTitle.Text = "Advanced"

 End If

 End If

 End If

 End If

 End If

 End If

End If

Visual Basic supports a statement, called Select Case, that handles such multiple-choice conditions better than If-Else. Here is the format of the Select Case statement:


Select Case Expression

Case value

 One or more Visual Basic statements

Case value

 One or more Visual Basic statements


[Case value

 One or more Visual Basic statements]

[Case Else:

 One or more Visual Basic statements]

End Select

The format of Select Case makes the statement look as difficult as a complex nested If-Else, but you will soon see that Select Case statements are actually easier to code and to maintain than their If-Else counterparts.

Expression can be any Visual Basic expression—such as a calculation, a string value, or a numeric value—provided that it results in an integer or string value. values must be integer or string values that match Expression’s data type.

The Select Case statement is useful when you must make several choices based on data values. Select Case can have two or more Case value sections. The code that executes depends on which value matches Expression. If none of the values match Expression, the Case Else body of code executes if you code the Case Else. Otherwise, nothing happens and control continues with the statement that follows End Select.



Warning: Don't use Select Case when a simply If or a simple If-Else will suffice. Test logic is often so straightforward that a Select Case would be overkill and even less clear than an If. Unless you need to compare against more than a couple of values, stick with the If and If-Else statements because of their simplicity.

Stop and Type: The fastest way to learn Select Case is to see an example of it. Listing 8.4 contains a Select Case version of the child grade assignments shown in Listing 8.3. Select Case organizes the multiple-choice selections into a more manageable format.

Review: The Select Case statement is a good substitute for long, nested If-Else conditions when one of several choices are possible. You set up your Visual Basic program to execute one set of Visual Basic statements from a list of statements inside Select Case.

Listing 8.4. Using Select Case to simplify complex nested If-Else statements.


1: Select Case Age

2: Case 5: lblTitle.Text = "Kindergarten"

3: Case 6: lblTitle.Text = 
"1st Grade"

4: Case 7: lblTitle.Text = "2nd Grade"

5: Case 8: lblTitle.Text = "3rd Grade"

6: Case 9: lblTitle.Text = "4th Grade"

7: Case 10: lblTitle.Text = "5th Grade"

8: Case 11: lblTitle.Text = 
"6th Grade"

9: Case Else: lblTitle.Text = "Advanced"

10: End Select

Analysis: If the Age variable holds the value 5, the label is assigned "Kindergarten" in line 2. If the Age variable holds the value 6, the label is assigned "1st Grade" in line 3. The logic continues through line 9. If Age holds a value that does not fall within the range of 5 through 11, line 9 assigns "Advanced" to the label.

The body of each Case can consist of more than one statement, just as the body of an If or If-Else can consist of more than one statement. Visual Basic executes all the statements for any given Case match until the next Case is reached. Once Visual Basic executes a matching Case value, it skips the remaining Case statements and continues with the code that follows the End Select statement.



Note: Programmers often trigger the execution of complete procedures, such as event procedures, from within a Case statement. As you will learn in Lesson 8, instead of putting several statements in the body of an If-Else or a Case, you can execute a procedure that contains all the statements that execute when a given condition is true.


Two Additional Select Case Formats


Concept: Visual Basic’s Select Case is one of the most powerful selection statements in any programming language. Pascal, C, and C++—all popular programming languages—each contain statements that act like Visual Basic’s Select Case, but Select Case offers two additional powerful formats that enable you to modify the way Case matches are made.

The two additional formats differ only slightly from the standard Select Case that you learned in the previous lesson. They enable you to extend the power of Select Case so that Visual Basic can make Case matches on both relational tests and on ranges of values. Here is the first additional format:


Select Case Expression

Case Is relation:

 One or more Visual Basic statements

Case Is relation:

 One or more Visual Basic statements


[Case Is relation:

 One or more Visual Basic statements]

[Case Else:

 One or more Visual Basic statements]

End Select

relation can be whatever relational test you want to perform against Expression at the top of the Select Case. The standard Select Case statement, discussed in the previous section, compared the Expression value against an exact Case match. When you use the relational Is Select Case option, each Case can be matched on a relational test.

Here is the format of the second additional Select Case format:


Select Case Expression

Case expr1 To expr2:

 One or more Visual Basic statements

Case expr1 
To expr2:

 One or more Visual Basic statements

[Case expr1 To expr2:

 One or more Visual Basic statements]

[Case Else:

 One or more Visual Basic statements]

End Select

The Case lines require a range, such as 4 To 6. The To Select Case option enables you to match against a range instead of a relation or an exact match.



Tip: You can combine the extended formats of Select Case with the standard Select Case so that two or more kinds of Case formats appear within the same Select Case statement.

[ic:Stop&Type]The code in Listing 8.4 contains a minor logic bug. The code handles all Age values over 11, but it does not handle Age values below 5. Therefore, if Age contains a value of 4, Listing 8.4 would assign "Advanced" to the label. However, if you add a relational test for the first Case, as shown in Listing 8.5, the code can handle any Age value.

Review: The additional Select Case options extend the power of Select Case beyond that of any selection statement in other languages. Using the two Case options that you learned in this section, you can code multiple-choice selections based on three kinds of matches:

Listing 8.5. Using Select Case to simplify complex nested If-Else statements.


1: Select Case Age

2: Case Is <5: lblTitle.Text = "Too young"

3: Case 5: lblTitle.Text = "Kindergarten"

4: Case 6: lblTitle.Text = 
"1st Grade"

5: Case 7: lblTitle.Text = "2nd Grade"

6: Case 8: lblTitle.Text = "3rd Grade"

7: Case 9: lblTitle.Text = "4th Grade"

8: Case 10: lblTitle.Text = "5th Grade"

9: Case 11: lblTitle.Text = 
"6th Grade"

10: Case Else: lblTitle.Text = "Advanced"

11: End Select

Analysis: By testing for a value less than 5 in line 1, Listing 8.5 ensures that both younger ages and older ages are covered by the Case selections.



Tip: Although the Case Else line is optional, be sure to code one unless you know the exact range of values that can match Expression.

[ic:Stop&Type]Listing 8.6 contains a similar Select Case problem that uses the To option for some of the Case values. Each Case tests against a range of possible values. The ages fall into categories, and the appropriate titles are updated depending on the category matches.

Listing 8.6. Using Select Case ranges for categorizing multiple matches.



1: Select Case Age

2: Case Is <5: lblTitle.Text = "Too young"

3: Case 5: lblTitle.Text = "Kindergarten"

4: Case 6 To 11: lblTitle.Text = "Elementary"

5: lblSchool.Text = "Lincoln"

6: 
Case 12 To 15: lblTitle.Text = "Intermediate"

7: lblSchool.Text = "Washington"

8: Case 16 To 18: lblTitle.Text = "High School"

9: lblSchool.Text = "Betsy Ross"

10: Case Else: lblTitle.Text = "College"


11: lblSchool.Text = "University"

12: End Select

Analysis: Listing 8.6 contains every Select Case option that exists. In the Select Case in line 1, the Age value is compared to its many possibilities throughout the rest of the Select Case. If Age holds a value less than 5, the label is updated in line 2 to reflect the child’s age. Nothing else executes. Visual Basic recognizes that the first Case in line 2 is a one-line Case, and the program continues with the line that follows End Select (line 12) as soon as line 2 finishes.

Line 3 compares the Age variable to the value of 5, and assigns "Kindergarten" to the label if Age is equal to 5.

Lines 4–9 compare whether Age falls within three different ranges of values and updates two label values accordingly. If all Case statements fail through line 9, the Case in line 10 takes over and assumes that Age holds a value greater than 18. (If Age holds any value less than 18, an earlier Case statement would have taken control.)

Homework



General Knowledge


  1. What is a condition?

  2. True or false: Relational tests produce one of three results.

  3. True or false: Visual Basic requires parentheses around a relational test.

  4. What are the six relational operators?

  5. Determine the true or false result of the following relational tests:

    1. "zz" < "ZZ"

    2. 161 <= 161

    3. 3.4 < 4

    4. (3 <> 4) And (5 = 5)

    5. (3 <> 4) Or (5 = 5)

    6. (3 = 3) And (10 < 9)

  6. What is the name of the table that determines how string values are compared?

  7. What Visual Basic statement makes decisions?

  8. What Visual Basic statement prescribes a true and a false course of action?

  9. True or false: The body of an If can contain more than one statement, but the body of the Else must contain one statement at most.

  10. What is a nested If statement?

  11. What statement helps eliminate tedious and convoluted If-Else statements?

  12. How many kinds of Case options are there?

  13. What happens if every Case fails and there is no Case Else option for a particular Select Case statement?

  14. What happens if every Case fails and there is a Case Else option on a particular Select Case statement?

  15. Which Case option tests for ranges of values?

  16. Which Case option tests for relational values?


Write Code That...


  1. Rewrite the following nested If statement using a single If with a logical operator:
    If (M = 3) Then
    If (P = 4) Then
    TestIt = "Yes"
    End If
    End If

  2. Rewrite the following If to eliminate the Not to clarify the code:
    If Not(d < 3) Or Not(p >= 9) Then

  3. Rewrite Listing 8.6 so that the message "Age Error" appears in the lblTitle.Text property if Age holds a value less than zero.


Find the Bug


  1. What is wrong with the following If statement?
    If (A < 1) And (C >= 8) Then
    lblName.Text = "Overdrawn"
    Else
    lblName.Text = "Underdrawn"
    End Else
    End If


Extra Credit


Given the following If and matching Select Case, which one is preferable and easier to maintain? Remember that you want to keep things simple and clear.
If (grade >= 70) Then
lblLetter.Text = "Passing"
Else
lblLetter.Text = "Failing"
End If
or
Select Case grade
Case Is >= 70: lblLetter.Text = "Pasing"
Case Else: lblLetter.Text = "Failing"
End Select

Previous Page Page Top TOC Next Page