'; zhtm += ''; zhtm += '

' + pPage + ''; zhtm += ''; window.popUpWin.document.write(zhtm); window.popUpWin.document.close(); // Johnny Jackson 4/28/98 } //--> Using Visual Basic 6 -- Ch 9 -- Working with Conditional Statements


Using Visual Basic 6

Previous chapterNext chapterContents


- 9 -
Working with Conditional Statements


Making Decisions in Your Program

Most statements in your programs will be assignment statements, but other statements are important for handling more complex tasks. These statements are known collectively as control statements. Without control statements, you couldn't write a very flexible program. Your program would start at the first line of code and proceed line by line until the last line was reached. At that point, the program would stop.

One type of control statement is the decision statement. These statements are used to control the execution of parts in your program, based on conditions that exist at the time the statement is encountered. Two main types of decision statements are If...Then and Select Case.


The IF Statement

Most programmers don't really understand the importance of the IF statement because it's so common in the programming environment. IF statements use comparison operators to test data values. Comparison operators or conditional operators test conditions that are either true or false. With this simple programming statement and its cousins, you can initiate complex calculations.


Writing If...Then Statements

In Visual Basic, you can write an If...Then statement for handling True conditions in two ways: the single-line If...Then statement and the multiline If...Then statement. Each uses the If...Then keywords to check a condition. If the condition is True, the program runs the commands associated with the If...Then statement. If the condition is False, the commands are skipped.

Writing a Single-Line If Statement

The single-line If statement is used to perform a single task when the condition in the statement is True. The following is the syntax of the single-line If statement:

If condition Then command

The condition represents any type of statement or function that evaluates to True. The condition can be any of the following:

The command represents the task to be performed if the condition is True. This can be any valid Visual Basic statement other than a variable declaration.

Look at the Simple Calculator program in Figure 9.1. The way this program works is that you enter a number in each of the two upper TextBoxes, select a math operation, and then click the CommandButton. The program performs the selected math operation on the numbers and displays the result in a third TextBox.

FIGURE 9.1 The Simple Calculator makes decisions in an If...Then statement, based on the value of the OptionButton.

The program decides which math operation to perform by evaluating the setting of the Value property of the OptionButton assigned to each operation. If the Value property of an OptionButton is set to True, the program does the associated math operation.

The following shows the If statement from the program. This conditional statement performs the associated math operation if True and is an example of a single-line If statement.

If optAddition.Value = True Then z = x + y

Listing 9.1 shows the entire code for the event procedure for the click of the cmdOperation CommandButton, the button that users click to perform the selected math operation.


Download this code

The source code for this program is the project simplclc.vbp, which is available on the Web at http://www.mcp.com/ info. You'll be asked to enter an ISBN; enter 078971633x and then click the Search button to go to the Book Info page for Using Visual Basic 6.


LISTING 9.1 09LIST01.TXT--Making Decisions Based on the Value of an
OptionButton

01 Private Sub cmdOperation_Click()
02 `Declare a variable for the first number
03 Dim x As Double
04
05 `Declare a variable for the second number
06 Dim y As Double
07
08 `Declare a variable to hold the sum of both numbers
09 Dim z As Double
10
11 `Convert the text inputted into the text box
12 `into an integer and assign it to the first variable
13 x = CDbl(txtNumOne.Text)
14
15 `Convert the text imputted into the text box
16 `into an integer and assign it to the second variable
17 y = CDbl(txtNumTwo.Text)
18
19 `Decide what operation to do based on the
20 `value of selected option but'ton
21 If optAddition.Value = True Then z = x + y
22
23 If optSubtraction.Value = True Then z = x - y
24
25 If optMultiplication.Value = True Then z = x * y
26
27 `For division, make sure that the second number is
28 `not equal to zero. You cannot divide a number by
29 `zero. Blows up!
30 If optDivision.Value = True Then
31 If y <> 0 Then
32 z = x / y
33 Else
34 `Report an error
35 MsgBox "Cannot divide by zero", vbCritical, "Error"
36 End If
37 End If
38 `Convert the third variable (which is a Double)
39 `to text and assign it to the text property of the
40 `textbox for the result.
41 txtTotal.Text = CStr(z)
42 End Sub

Executing Multiple Commands in the Conditional Statement

If you need to execute more than one command in response to a condition, you can use a block If...Then statement. A block If...Then statement bounds a range of statements between the If...Then statement and an End If statement. If the condition in the If...Then statement is True, all the commands between the If...Then and End If statements are run. If the condition is False, the program skips to the first line after the End If statement.

The structure of a multiple-command If statement is as follows:

If condition Then
     Command1
     Command2
     Commandn
End If

in which If and Then are the Visual Basic keywords that "bracket" the condition, and End If are the keywords that end the code block.

Listing 9.2 shows a portion of code that enhances the cmdOperation_Click() event procedure from Listing 9.1.

LISTING 9.2 09LIST02.TXT--Using Multiple Commands in an If...Then
Statement

01 `Decide what operation to do based on the
02 `value of selected option button
03 If optAddition.Value = True Then
04 z = x + y
05 frmMain.Caption = "Addition"
06 End If
07
08 If optSubtraction.Value = True Then
09 z = x - y
10 frmMain.Caption = "Subtraction"
11 End If
12
13 If optMultiplication.Value = True Then
14 z = x * y
15 frmMain.Caption = "Multiplication"
16 End If

Whereas the code in Listing 9.1 invokes only one command when an If...Then statement evaluates True (see line 21 of Listing 9.1), the code in Listing 9.2 invokes two commands when the If...Then statement evaluates True (see lines 3-6 in Listing 9.2).

Using If...Then...Else Statements

As you learned earlier, sometimes you might encounter this situation: If one condition exists, you do one set of commands, and if it doesn't, you do another set. For example, If you have money in your checking account, write a check; Else, transfer funds from your savings account into the checking account. This is called an If...Then...Else statement. If...Then...Else takes the following format:

If condition Then
     statements to process if condition is True
Else
     statements to process if condition is False
End If

The If and End If statements of this block are the same as before. The condition is still any logical expression or variable that yields a True or False value. The key element in this set of statements is the Else statement. This statement is placed after the last statement to be executed if the condition is True, and before the first statement to be executed if the condition is False. For a True condition, the program processes the statements up to the Else statement and then skips to the first statement after the End If. If the condition is False, the program skips the statements before the Else statement and starts processing with the first statement after the Else.

You saw the following code snippet at the end of Listing 9.1. This is an excellent example of a simple If...Then...Else statement. If the value of the variable y doesn't equal zero (line 30), the program does some division (line 31); otherwise, the program displays a Windows message box with an error message (line 34).

30  If optDivision.Value = True Then
31    If y <> 0 Then
32        z = x / y
33    Else
34      `Report an  error
35      MsgBox "Cannot divide by zero", vbCritical, "Error"
36    End If
37  End If

If you want to execute code for only the False portion of the statement, you can place code statements between the Else and End If statements; you aren't required to place any statements between the If and Else statements:

If x <= 1 then
Else
    MsgBox "X is not greater than 1"
End If

Working with Multiple If Statements

In the preceding sections, you saw simple If...Then statements, which evaluate one condition and can execute commands for a True or False condition. You can also evaluate multiple conditions with an additional statement in the block. If...Then...ElseIf statements let you specify another condition to evaluate whether the first condition is False. By using the ElseIf statement, you can evaluate any number of conditions.

Listing 9.3 shows a snippet of code from the program Grader.EXE (see Figure 9.2) from the project grader.vbp, available from the Web site associated with this book. The code snippet uses the ElseIf conditional structure as a way to determine the grade for a test, based on a range of correct answers.

FIGURE 9.2 The Grader program uses If...Then...ElseIf statements to determine a grade based on correct answers.

LISTING 9.3 09LIST03.TXT--Using ElseIf Statements to Evaluate Multiple
Conditions

01 If CorrectAnswers% >= 10 Then
02 strGrade = "A"
03 ElseIf CorrectAnswers% = 9 Then
04 strGrade = "A-"
05 ElseIf CorrectAnswers% = 8 Then
06 strGrade = "B"
07 ElseIf CorrectAnswers% = 7 Then
08 strGrade = "B-"
09 ElseIf CorrectAnswers% = 6 Then
10 strGrade = "C"
11 ElseIf CorrectAnswers% = 5 Then
12 strGrade = "C-"
13 ElseIf CorrectAnswers% = 4 Then
14 strGrade = "D"
15 ElseIf CorrectAnswers% = 3 Then
16 strGrade = "D-"
17 Else
18 strGrade = "F"
19 End If

This code works first by evaluating the condition in the If statement (line 1). If the condition is True, the statement (or statements) immediately following the If statement is executed (line 2), and then the program skips to the first statement after the End If statement (line 19).

If the first condition is False, the program skips to the first ElseIf statement (line 3) and evaluates its condition. If this condition is True, the statements following the ElseIf are executed (line 4), and control again passes to the statement after the End If. If the condition evaluates to False, control passes to the next ElseIf statement. This process continues for as many ElseIf statements as are in the block.

If all the conditions are False, the program skips to the Else statement and processes the commands between the Else (line 17) and the End If statements. The Else statement isn't required.

Using Nested If Statements

If you need to test for a condition that depends on whether another condition is already True (such as "If it's 6:30 a.m. and if it's a weekday"), use nested If statements. A nested If statement is one that's enclosed within another If statement. The format for a nested If statement is as follows:

If condition Then
   If another_condition Then
       statement
   Else
       another statement
   End If
End If

The following code snippet demonstrates a nested If statement. You originally saw it in the cmdOperation Click() event procedure in Listing 9.1.

30  If optDivision.Value = True Then
31    If y <> 0 Then
32        z = x / y
33    Else
34      `Report an  error
35      MsgBox "Cannot divide by zero", vbCritical, "Error"
36    End If
37  End If

Using the Select Case Statement

Another way to handle decisions in a program is to use the Select Case statement, which enables you to run any of a series of statement groups, based on the value of a single variable. The Select Case statement identifies the variable to be evaluated, and then a series of Case statements specifies the possible values. If the value of the variable matches the value (or values) indicated in the Case statement, the commands after the Case statement are executed. If the value doesn't match, the program proceeds to the next Case statement.

The Select Case structure is similar to a series of If...Then...ElseIf statements. The following lines of code show the syntax of the Select Case block:

Select Case TestValue
     Case Value1
          Statement_Group_1
     Case Value2
          Statement_Group_2
End Select


Correct character order

Pay particular attention to the order of characters in the less-than and greater-than symbols. They must be ordered as shown previously. Using => or =< will produce an error.




Select Case limitations

You should never use Select Case if a simple If...Then...Else statement will work. Sometimes using Select Case can be overkill and add to the confusion that complex logic statements can provide.


The first statement of the Select Case block is the Select Case statement itself. This statement identifies the value to be tested against possible results. This value, represented by the TestValue argument, can be any valid numeric or string expression, including a literal, a variable, a logical expression, or a function.

Each conditional group of commands (run if the condition is met) is started by a Case statement. The Case statement identifies the expression to which the TestValue is compared. The Case statement can express a single value or a range of values. If the TestValue is equal to or within range of the expression, the commands after the Case statement are run. The program runs the commands between the current Case statement and the next Case statement or the End Select statement. If the TestValue isn't equal to the value expression or doesn't fall within a range defined for the Case statement, the program proceeds to the next Case statement.

Listing 9.4 shows you a Select Case statement that tests for equality. Listing 9.5 shows you a Select Case statement that tests for a range.

LISTING 9.4 09LIST04.TXT--Testing for Equality in a Select Case Statement

01 Select Case x%
02 Case 1:
03 MsgBox "I am 1"
04 Case 2:
05 MsgBox "I am 2"
06 End Select

LISTING 9.5 09LIST05.TXT--Testing for a Range in a Select Case Statement

01 Select Case x%
02 Case 6 To 9
03 MsgBox "I am more than 5 and less than 10"
04 Case 101 To 199
05 MsgBox "I am more than 100 and less than 200"
06 Case Else
07 MsgBox "Not in Range"
08 End Select

The simplest form of the Select Case block uses only a single value for the comparison expression. Listing 9.6 shows a Select Case statement that accomplishes the same thing that the If...Then...ElseIf code in Listing 9.3 does. The benefit of using a Select Case to accomplish the grading task is that the code is easier to read and easier to extend.

LISTING 9.6 09LIST06.TXT--Rewriting an If...Then...ElseIf Statement as a
Select Case Statement

01 Private Sub cmdGrader_Click()
02 Dim CorrectAnswers%
03 Dim strGrade As String
04
05 `Get the correct answers from the textbox
06 CorrectAnswers% = CInt(txtNumberRight.Text)
07
08 `Assign the grade based on the correct answers
09 Select Case CorrectAnswers%
10 Case 10
11 strGrade = "A"
12 Case 9
13 strGrade = "A-"
14 Case 8
15 strGrade = "B"
16 Case 7
17 strGrade = "B-"
18 Case 6
19 strGrade = "C"
20 Case 5
21 strGrade = "C-"
22 Case 4
23 strGrade = "D"
24 Case 3
25 strGrade = "D-"
26 Case Else
27 strGrade = "F"
28 End Select
29 `Display the grade
30 lblGrade.Caption = strGrade
31 End Sub

When it comes time to add another grade level--say, an A+ if the student correctly answers 11 in the following example--all you need is to add a new case, Case 11 (see Listing 9.7, line 3). If you were to use the ElseIf technique, you would have to rewrite significant portions of the If...Then...ElseIf code block.

LISTING 9.7 09LIST07.TXT--Extending a Select Case Statement

01 Select Case CorrectAnswers%
02 `Add a case for 11 correct answers
03 Case 11
04 strGrade = "A+"
05 Case 10
06 strGrade = "A"
07 Case 9
08 strGrade = "A-"
09 Case 8
10 strGrade = "B"
11 Case 7
12 strGrade = "B-"
13 Case 6
14 strGrade = "C"
15 Case 5
16 strGrade = "C-"
17 Case 4
18 strGrade = "D"
19 Case 3
20 strGrade = "D-"
21 Case Else
22 strGrade = "F"
23 End Select

Using Relational Operators in Select Case Blocks

You can also use relational operators in a Select Case block. Sometimes you might want to test for cases within a range perhaps greater than or less than a certain number. To accomplish this with a Select Case block, you must use the Is keyword. To test within a certain range, use the To keyword as you saw earlier in Listing 9.5.

Just as you can check to see whether equality exists between two quantities with the = sign, you can also check to see whether numbers are less than, greater than, or not equal to one another. Table 9.1 shows the relational operators that you can use in your conditional statements.


Correct character order

Pay particular attention to the order of characters in the less-than and greater-than symbols. They must be ordered as shown previously. Using => or =< will produce an error.


TABLE 9.1 Relational Operators

Symbol Meaning Example Result
= Equal 8 = 9 False
> Greater than 8 > 9 False
< Less than 8 < 9 True
>= Greater than or equal to 8 >= 8 True
<= Less than or equal to 7 <= 6 False
<> Not equal to 6 <> 7 True

Line 3 of Listing 9.8 shows you how to use the Is keyword to create a greater-than statement within a Select Case block. Notice that the relational operator (>) is used to make any number of correct answers greater than 11 result in a grade of A++.


Download this code!

The complete project to which this code applies is Grader2.vbp, which you can find on the Web, as explained earlier.


LISTING 9.8 09LIST08.TXT--Using Relational Operators with Select Case Statements

01 Select Case CorrectAnswers%
02 `Make any answer greater than 11 an A++
03 Case Is > 11
04 strGrade = "A++"
05 Case 11
06 strGrade = "A+"
07 Case 10
08 strGrade = "A"
09 Case 9
10 strGrade = "A-"
11 Case 8
12 strGrade = "B"
13 Case 7
14 strGrade = "B-"
15 Case 6
16 strGrade = "C"
17 Case 5
18 strGrade = "C-"
19 Case 4
20 strGrade = "D"
21 Case 3
23 strGrade = "D-"
24 Case Else
25 strGrade = "F"
26 End Select

Select Case statements are a powerful addition to your programming toolkit and take you to the next level of programming expertise. As you learn more about them, you will understand how to use If statements and Select Case statements together to make very detailed, extended decisions within your programs.


Previous chapterNext chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.