If…ElseIF Statement

When there are more than two possible actions to take we sometimes use a serial if statement.

Format of a serial if statement in Visual Basic

If condition Then

‘Note: you may have one or more statement
statement
statement

ElseIf condition Then

statement
statement

ElseIf condition Then

statement

Else

statement
statement

End if

For example

If txtinput.Text = "" Then
       MsgBox(
"you must enter a value in the TextBox")
ElseIf IsNumeric(txtinput.Text) Then
       MsgBox(
"you entered the number " & txtinput.Text )
Else
       MsgBox(
"you entered the string " & txtinput.Text )
End If

Another example

If sngSales < 1000 Then
       sngCommissionRate = .10
ElseIf sngSales < 5000  Then
       sngCommissionRate = .11
ElseIf sngSales < 10000  Then
       sngCommissionRate = .12
Else
      sngCommissionRate = .13
End If


Consider: Can you write the preceding selection structure using only simple block if statements? If Yes how? If not why not?

 

 

Can you write the following statement using simple block if statements? If Yes how? If not why not?

If strEmployeeCode.ToUpper = “S” Then
      strStatus =
“Salaried”
ElseIf strEmployeeCode.ToUpper = “H” Then
     strStatus =
“Hourly”
Else
     strStatus =
“Contractual”
End If



Unlike the simple If..Then..Else..EndIf statement which can also be written as a series of simple block If statements the If..Then..ElseIf..Else..EndIf often cannot be (at least cannot be using "good" code).

ElseIf is one word. What do you think the compiler would do with the following segment of code?

If strEmployeeCode.ToUpper = “S” Then
      strStatus =
“Salaried”
Else
     
If strEmployeeCode.ToUpper = “H” Then
           strStatus = “
Hourly”
     
Else
           strStatus =
“Contractual”
End If

 
 

 

Error -    

no end If error messge


  
Every If requires an End If statement. ElseIfs do not.

If strEmployeeCode.ToUpper = “S” Then
      strStatus =
“Salaried”
Else
     
If strEmployeeCode.ToUpper = “H” Then
           strStatus = “
Hourly”
     
Else
           strStatus =
“Contractual”
     
EndIf
End If

Notice the alignment of the instructions. If should always be aligned with its corresponding Else and End If statements. Visual Basic 2010 does this automatically.

The preceding code would be better written


If strEmployeeCode.ToUpper = “S” Then
      strStatus =
“Salaried”
ElseIf strEmployeeCode.ToUpper = “H” Then
           strStatus = “
Hourly”
Else
           strStatus =
“Contractual”
End If