With the simple selection we did something when the stated condition was True and did nothing when it was False.
When we want to do something when a condition is True and something different when the condition is False we use the word Else
The If ... Else Statement in Visual Basic
If condition
Then
statement
statement
Else
statement
statement
End If
In a block If statement the If condition is on a line by itself as is End If. The Else is generally on a line by itself but it is not required to be.
For example:
If txtInput.Text = ""
Then
MsgBox ("you must enter a value in the TextBox")
Else
‘Will be executed when txtInput.Text is NOT = “”
MsgBox ("you entered " & txtInput.Text)
End If
The introduction of selection allows for a wider variety of code. The following sections of code will result in the same outcome.
If intTestScore > 69
Then
strGrade =
“Pass”
Else
strGrade
“Fail”
End If
is the same as
If intTestScore > 69
Then
strGrade = “Pass”
End If
If intTestScore <= 69
Then
strGrade = “Fail”
End If
Neither way is more “correct” than the other but you may believe that one is clearer than the other.
Another example
If sngHours <= 40
Then
sngRegular = sngHours * sngRate
sngOvertime = 0
Else
sngRegular = 40 * sngRate
sngOvertime = (sngHours – 40) _
* (sngRate * 1.5)
End if
Will result in the same outcome as
If sngHours <= 40
Then
sngRegular = sngHours * sngRate
sngOvertime = 0
End If
If snghours > 40
Then
sngRegular = 40 * sngRate
sngOvertime = (sngHours – 40) _
* (sngRate * 1.5)
End If
And
If intTicketsSold = intTicketsAvailable
Then
MsgBox (“Sold Out”)
Else
MsgBox (“Tickets Available”)
End If
Is the same as -
If intTicketsSold = intTicketsAvailable
Then
MsgBox (
“Sold Out”)
End If
If intTicketsSold < > intTicketsAvailable
Then
MsgBox (“Tickets Available”)
End If
Consider: Do you see a flaw in the preceding logic?