Compound Comparisons with the Logical OperatorsVisual Basic supports three additional operators - And, Or, and Not[md]that look more like commands than operators. And, Or, and Not are logical operators. Logical operators let you combine two or more comparison tests into a single compound comparison. Table 7.3 describes the logical operators, which work just like their spoken counterparts. Table 7.3. The logical operators.
As you can see from Table 7.3, the And and Or logical operators let you combine more than one comparison test in a single If statement. The Not negates a comparison test. You can often turn a Not condition around. Not can produce difficult comparison tests, and you should use it cautiously. The last If in Table 7.3, for instance, could easily be changed to If (strAns <> 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 salesperson if sales total more than $5,000 and if the salesperson 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 like this: If (sngSales > 5000.00) Then If (intUnitsSold > 10000) Then sngBonus = 50.00 End If End If Here is the same code rewritten as a single If. It is easier to read and to change later if you need to update the program: If (sngSales > 5000.00) And (intUnitsSold > 10000) Then sngBonus = 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 the salesperson sells more than 10,000 units? Here is the code: If (sngSales > 5000.00) Or (intUnitsSold > 10000) Then sngBonus = 50.00 End If Listing 7.2 contains an If...Else that tests data from two divisions of a company and calculates values from the data. Listing 7.2. Calculating sales figures for a companys divisions. 1: If (intDivNum = 3) Or (intDivNum = 4) Then 2: curDivTotal = curDivSales3 + curDivSales4 3: curGrandDivCosts = (curDivCost3 * 1.2) + (curDivCost4 * 1.4) 4: Else 5: curDivTotal = curDivSales1 + curDivSales2 6: curGrandDivCosts = (curDivCost1 * 1.1) + (curDivCost5 * 1.9) 7: End If If intDivNum contains either a 3 or a 4, the user is requesting figures for the East Coast, and the code in the first If branch executes to produce an East Coast pair of values. If intDivNum doesnt contain a 3 or a 4, the program assumes that intDivNum contains a 1 or a 2, and the West Coast pair of values is calculated in the Else portion.
|
|||||||||||||
![]() |
![]() |
|||