Sometimes, you just have to make some choices, and conditional expressions will help you do just that. Visual Basic includes support for conditions, which use data tests to determine which code should be processed next.

If Statements

The most common conditional statement is the If statement. It is equivalent to English questions in the form, "If such-and-such is true, then do so-and-so." For instance, it can handle, "If you have $20, then you can buy me dinner," but not, "If a train departs Chicago at 45 miles per hour, when will it run out of coal?"

If statements have a syntax that spans multiple source code lines.

01 If (hadAHammer = True) Then 02    DoHammer(inTheMorning, allOverThisLand) 03    DoHammer(inTheEvening, allOverThisLand) 04 ElseIf (hadAShovel = True) Then 05    DoShovel(inTheNoontime, allOverThisLand) 06 Else 07    TakeNap(allDayLong, onMySofa) 08 End If 

The If statement lets you define branches in your code based on conditions. It is built from three main components.

  1. Conditions. The expression found between the If (or ElseIf) keyword and the Then keyword is the condition. The sample includes two conditions, on lines 01 and 04. Conditions may be simple or complex, but they must already result in a Boolean True or False value. They can include calls to other functions and multiple logical and comparison operators.

    If ((PlayersOnTeam(homeTeam) >= 9) And _       (PlayersOnTeam(visitingTeam) >= 9)) Or _       (justPracticing = True) Then    PlayBall() Else    StadiumLights(turnOff) End If 

    The original condition always follows the If keyword. If that conditions fails, you can specify additional conditions following an ElseIf keyword, as on line 04. You may include as many ElseIf clauses as you need.

  2. Branches. Each condition's Then keyword is followed by one or more Visual Basic statements that are processed if the associated condition evaluates to True. All statements up to the next ElseIf or the final End If are included in that branch's statement block. You may include any number of statements in a branch block, including additional subordinate If statements. In the sample code, branch lines 02 and 03 are processed if the original "hadAHammer" condition is true. Line 05 is processed instead if the original condition fails, but the second "hadAShovel" condition passes. If none of the conditions are True, the Else's branch, on line 07, executes.

  3. Statement keywords. The If statement is one of several multi-line statements in Visual Basic, all of which end with the keyword End followed by the original statement keyword (If in this case). The If statement's keywords, which give the statement its structure, include If, Then, ElseIf, Else, and End If. All ElseIf and Else clauses and related branches are optional. The simplest If statement includes only an If branch.

    If (phoneNumberLength = 10) Then    DialNumber(phoneNumber) End If 

    For conditions with simple single-statement branches and no ElseIf clauses, a single-line alternative can keep your code looking clean.

    If (SaveData() = True) Then MsgBox("Data saved.") If (TimeOfDay >= #13:00#) _    Then currentStatus = WorkStatus.GoHome _    Else currentStatus = WorkStatus.BusyWorking 

If statements are cool because they make your code more than just a boring set of linear step-by-step instructions that never deviate for any reason. Software is written to support some real-world process, and real-world processes are seldom linear. The If statement makes it possible for your code to react to different data conditions, taking the appropriate branch when necessary.

Once the entire If . . . End If block completes, processing continues with the next statement that follows the End If statement.

Select Case Statements

Sometimes you might write an If statement that simply tests a variable against one possible value, then another, then another, then another, and so on.

If (billValue = 1) Then    presidentName = "Washington" ElseIf (billValue = 2) Then    presidentName = "Jefferson" ElseIf (billValue = 5) Then    presidentName = "Lincoln"    ... 

And on it goes, through many more ElseIf clauses. It's effective, but a little tedious, as your code must specifically test every case. The Select Case statement provides a cleaner alternative to simple value comparisons against a list.

01 Select Case billValue 02    Case 1 03       presidentName = "Washington" 04    Case 2 05       presidentName = "Jefferson" 06    Case 5 07       presidentName = "Lincoln" 08    Case 20 09       presidentName = "Jackson" 10    Case 50 11       presidentName = "Grant" 12    Case 10, 100 13       presidentName = "!! Non-president" 14    Case > 100 15       presidentName = "!! Value too large" 16    Case Else 17       presidentName = "!! Invalid value" 18 End Select 

Unlike the If statement, which checks for a Boolean result, Select Case compares a single value against a set of test case values. In the example, the billValue variable is compared against the different values identified by each Case clause. All code that follows a Case clause (until the next Case clause) is the branch that is processed when a match is found. An optional Case Else condition (line 16) catches anything that is not matched by any other Case. Normally, Case clauses list single values for comparison. They can also include a list of comma-separated comparison values (line 12), or simple range comparison expressions (line 14).

IIf Function

Visual Basic includes a variation of the If statement for "in line" use. Consider the following statement.

If (gender = "F") Then fullGender = "Female" _    Else fullGender = "Male" 

Using the IIf function, this statement compresses into a single assignment statement with an embedded condition.

fullGender = IIf(gender = "F", "Female", "Male") 

The IIf function has three comma-delimited arguments. The first is the condition, which must result in a Boolean True or False value. The second argument is returned by the function if the condition is True; a condition result of False returns the third argument. For simple conditions that are destined to return single values to a common variable, it's really a useful function. But with anything really useful, there are caveats. The caveat with IIf is that anything appearing inside the IIf statement will be processed, even if it is not returned as a result. Here's a dangerous example:

purgeResult = IIf(level = 1, PurgeSet1(), PurgeSet2()) 

The statement will correctly return the result of either PurgeSet1() or PurgeSet2() based on the value of level. The problem, or potential problem, is that both functions, PurgeSet1() and PurgeSet2(), will be called; if level is 1, both PurgeSet1() and PurgeSet2() will be called, even though only the function result from PurgeSet1() will be returned.

Start-to-Finish Visual Basic 2005. Learn Visual Basic 2005 as You Design and Develop a Complete Application
Start-to-Finish Visual Basic 2005: Learn Visual Basic 2005 as You Design and Develop a Complete Application
ISBN: 0321398009
EAN: 2147483647
Year: 2006
Pages: 247
Authors: Tim Patrick © 2008-2017.
If you may any questions please contact us: