O'Reilly logo

Programming Visual Basic 2008 by Tim Patrick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Conditions

Sometimes you 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 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:

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 always 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required