vel08.htm
来自「简单的说明如何使用VB,非常适合初学使用者,而且是用图表来解说的」· HTM 代码 · 共 1,958 行 · 第 1/3 页
HTM
1,958 行
</BLOCKQUOTE></BLOCKQUOTE><P><FONT COLOR="#FF8000"><B><I>Review: </I></B></FONT>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.<BR><BR><A NAME="E68E63"></A><H3 ALIGN=CENTER><CENTER><FONT SIZE=5 COLOR="#FF0000"><B>The </B><FONT COLOR="#FF8000"><B><I>If</I></B></FONT><B> Makes Decisions</B></FONT></CENTER></H3><BR><P><FONT COLOR="#FF8000"><B><I>Concept: </I></B></FONT>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 <I>might</I> execute one or more lines of subsequent code, depending on the results of the test.<BR><P>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:<BR><PRE><FONT COLOR="#000080">If relationalTest Then One or more Visual Basic statementsEnd If</FONT></PRE><P>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:<BR><PRE><FONT COLOR="#000080">If (txtSales.Text > 5000.00) Then Bonus = Val(txtSales.Text) * .12End If</FONT></PRE><P>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:<BR><P><I>If the sales are more than $5,000.00, then compute a bonus based on that sales value.</I><BR><P>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:<BR><PRE><FONT COLOR="#000080">If (txtSales.Text > 5000.00) Then Bonus = Val(txtSales.Text) * .12 CostOfSales = Val(txtSales.Text) * .41 ReorderCost = Val(txtSales.Text) * .24End If</FONT></PRE><P>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:<BR><PRE><FONT COLOR="#000080">If (txtSales.Text > 5000.00) Then Bonus = Val(txtSales.Text) * .12 CostOfSales = Val(txtSales.Text) * .41 ReorderCost = Val(txtSales.Text) * .24End IfTax = .12 * Val(txtSales.Text)</FONT></PRE><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><B>Tip: </B>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.</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><P>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.<BR><P>There is a shortcut form of If that you might run across. The <I>single-line </I><I>If</I><I> statement </I>has a format that looks like this:<BR><BR><PRE><FONT COLOR="#000080">If relationalTest Then VBStatement</FONT></PRE><P>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.<BR><P><FONT COLOR="#FF8000"><B><I>Review: </I></B></FONT>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.<BR><BR><A NAME="E68E64"></A><H3 ALIGN=CENTER><CENTER><FONT SIZE=5 COLOR="#FF0000"><B>Handling False Conditions</B></FONT></CENTER></H3><BR><P><FONT COLOR="#FF8000"><B><I>Concept: </I></B></FONT>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.<BR><P>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:<BR><PRE><FONT COLOR="#000080">If relationalTest Then One or more Visual Basic statementsElse One or more Visual Basic statementsEnd If</FONT></PRE><P>Typically, programmers call this full-blown If statement the If-Else statement. The If-Else statement is sometimes called a <I>mutually exclusive</I> statement. The term <I>mutually exclusive</I> 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.<BR><P><FONT COLOR="#FF8000"><B><I>Stop & Type:</I></B></FONT> 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.<BR><P>Listing 8.1 contains a <I>code fragment</I>—sometimes called a <I>code snippet</I>—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.<BR><P><FONT COLOR="#FF8000"><B><I>Review: </I></B></FONT>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.<BR><P><FONT COLOR="#000080"><B>Listing 8.1. Determining a sales bonus or penalty.</B></FONT><BR><PRE><FONT COLOR="#000080">1: If (Val(txtSales.Text) > 5000.00) Then2: Bonus = .05 * Val(txtSales.Text)3: Else4: PayAmt = PayAmt - 25.005: End If6: Taxes = PayAmt * .42</FONT></PRE><P><FONT COLOR="#FF8000"><B><I>Analysis: </I></B></FONT>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.<BR><P>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).<BR><P>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.<BR><P><B> <A HREF="08vel01.gif">Figure 8.1. Either the </B><B>If</B><B> body or the </B><B>Else</B><B> body executes, but not both.</A></B><BR><P>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 <I>nothing</I> 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.<BR><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><B>Note: </B>When a variable appears on both sides of an assignment's equal sign, the variable is being <I>updated</I> in some way.</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><BR><A NAME="E68E65"></A><H3 ALIGN=CENTER><CENTER><FONT SIZE=5 COLOR="#FF0000"><B>Logical Operators</B></FONT></CENTER></H3><BR><P><FONT COLOR="#FF8000"><B><I>Concept: </I></B></FONT>Three additional operators, And, Or, and Not, look more like commands than operators. And, Or, and Not are called <I>logical operators</I>. 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.<BR><P>Table 8.3 describes the logical operators, which work just like their spoken counterparts.<BR><BR><P ALIGN=CENTER><CENTER><FONT COLOR="#000080"><B>Table 8.3. The logical operators.</B></FONT></CENTER><BR><TABLE BORDERCOLOR=#000040 BORDER=1 CELLSPACING=2 WIDTH="100%" CELLPADDING=2 ><TR><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080><I>Operator</I></FONT><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080><I>Usage</I></FONT><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080><I>Description</I></FONT><TR><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>And</FONT><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>If (A > B) And (C < D)</FONT><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>Returns true if both sides of the And are true. Therefore, A must be greater than B <I>and</I> C must be less than D. Otherwise, the expression returns a false result.</FONT><TR><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>Or</FONT><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>If (A > B) Or (C < D)</FONT><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>Returns true if either side of the Or is true. Therefore, A must be greater than B <I>or</I> C must be less than D. If both sides of the Or are false, the entire expression returns a false result.</FONT><TR><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>Not</FONT><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>If Not(Ans = "Yes")</FONT><TD VALIGN=top BGCOLOR=#80FFFF ><FONT COLOR=#000080>Produces the opposite true or false result. Therefore, if Ans holds "Yes", the Not turns the true result to false.</FONT></TABLE><P>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.<BR><P>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,<BR><PRE><FONT COLOR="#000080">If (Sales > 5000.00) Then If (UnitsSold > 10000) Then Bonus = 50.00 End IfEnd If</FONT></PRE><P>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.<BR><PRE><FONT COLOR="#000080">If (Sales > 5000.00) And (UnitsSold > 10000) Then Bonus = 50.00End If</FONT></PRE><P>How can you rewrite this If to pay the bonus if the salesperson sells <I>either</I> more than $5,000 in sales <I>or</I> if he sells more than 10,000 units? Here is the code:<BR><PRE><FONT COLOR="#000080">If (Sales > 5000.00) Or (UnitsSold > 10000) Then Bonus = 50.00End If</FONT></PRE><P><FONT COLOR="#FF8000"><B><I>Stop and Type:</I></B></FONT> Listing 8.2 contains an If-Else that tests data from two divisions of a company and calculates values from the data.<BR><P><FONT COLOR="#FF8000"><B><I>Review: </I></B></FONT>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.<BR><P><FONT COLOR="#000080"><B>Listing 8.2. Calculating sales figures for a company’s divisions.</B></FONT><BR><PRE><FONT COLOR="#000080">1: If (DivNum = 3) Or (DivNum = 4) Then2: DivTotal = DivSales3 + DivSales43: GrandDivCosts = (DivCost3 * 1.2) + (DivCost4 * 1.4)4: Else5: DovTotal = DivSales1 + DivSales26: GrandDivCosts = (DivCost1 * 1.1) + (DivCost5 * 1.9)7: End If</FONT></PRE><P><FONT COLOR="#FF8000"><B><I>Analysis: </I></B></FONT>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.<BR><P>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.<BR><BR><A NAME="E68E66"></A><H3 ALIGN=CENTER><CENTER><FONT SIZE=5 COLOR="#FF0000"><B>Multiple Choice with </B><FONT COLOR="#FF8000"><B><I>Select Case</I></B></FONT></FONT></CENTER></H3><BR><P><FONT COLOR="#FF8000"><B><I>Concept: </I></B></FONT>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.<BR><P>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.<BR><P><FONT COLOR="#000080"><B>Listing 8.3. Nested </B><B>If</B><B>-</B><B>Else</B><B> statements get complex quickly.</B></FONT><BR><PRE><FONT COLOR="#000080">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 IfEnd If</FONT></PRE><P>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:<BR><PRE><FONT COLOR="#000080">Select Case <I>Expression</I>Case <I>value</I><I> One or more Visual Basic statements</I>Case <I>value</I><I> One or more Visual Basic statements</I>[Case <I>value</I><I> One or more Visual Basic statements</I>][Case Else:<I> One or more Visual Basic statements</I>]End Select</FONT></PRE><P>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.<BR><P><I>Expression</I> 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. <I>value</I>s must be integer or string values that match <I>Expression</I>’s data type.<BR><P>The Select Case statement is useful when you must make several choices based on data values. Select Case can have two or more Case <I>value</I> sections. The code that executes depends on which <I>value</I> matches <I>Expression</I>. If none of the <I>value</I>s match <I>Expression</I>, 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.<BR><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><B>Warning: </B>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.</NOTE><BR>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?