The If-Then-Else Statement
You have seen the If-Then-Else statement in several programs in earlier chapters, and in this section, you're going to learn the details. This is the syntax for the If-Then-Else statement:
If Expression1 Then ' Execute this statement block if Expression1 True Else ' Execute this statement block if Expression1 False End If
If Expression1 evaluates to logic True , the statement block following the Then keyword is executed. This is exactly the same as in a simple If statement. If Expression1 evaluates to logic False , the statement block following the Else keyword is executed.
You can make a simple modification to the IfElseProject program from earlier in this chapter to illustrate how the If-Then-Else statement works. Change the existing code in the btnTest object's Click() event to this:
If OddEven(Number) Then txtResult.Text = "Odd" ' Then statement block Else txtResult.Text = "Even" ' Else statement block End If
Notice that you have added the Else statement to the If block. Also, you have moved the assignment of "Even" to txtResult into the Else statement block. If the call to OddEven() returns 1 , the Then component of the If block is executed, and "Odd" is assigned to txtResult . If the call to OddEven() returns , the Else component of the If block is executed, and "Even" is assigned in txtResult .
The If Statement Block, the Then Statement Block, and the Else Statement Block
An If-Then-Else statement actually has three statement blocks. The first is the If statement block, which extends from the keyword If to the End If keywords. Within the If-Then-Else statement block are two more statement blocks: the Then and Else statement blocks. There can be one or more statements in the Then and Else statement blocks.
You can think of the Else keyword as serving a dual role. First, the Else keyword marks the end of the Then statement block. Any statements after the Then keyword but before the Else keyword are part of the Then statement block. Second, the Else keyword marks the start of the Else statement block. Any statements after the Else keyword but before the End If keywords are part of the Else statement block.
The If statement block encompasses both the Then and Else statement blocks. Sometimes you'll hear a programmer say something like, "The If block calls the OddEven() function. " In most cases, the programmer is referring to the entire If statement block, including the Then and Else blocks.