The multiway If statement

The two-way If statement is applied when you want the program code to execute one set of instructions if some condition is true, else execute another set of instructions. However, there are times when you may want to execute one set of instructions if some condition is true, or else if some other condition is true, you may want to execute another set of instructions, and so on, until all alternatives have been completed. The general syntax is:

If ComparisonTest Then

One or more VBA statements Else If

One or more VBA statements Else If

One or more VBA statements Else

One or more VBA statements End If

Consider the previous example. This was written as a two-way If, where the first condition checked if the person's sex was female and displayed the appropriate message, else the alternative message for a male person would be displayed. The problem is that the program would take any alternative value other than female. We will extend this two-way If to a three-way If so that first condition will check if the person's sex is female and display the appropriate message, else if the person's sex is male, it will display the male message, else it will display an error message such as "You have entered an invalid sex". In Listing 6.4, the If checks if the sex is female and display the corresponding message. Else If checks if the sex is male, will display the corresponding, and the final Else will display an error message.

Sub retire_age () Dim sex As String

Sex = InputBox ("Input the sex of the person (male or female)", "Person's Sex") If (sex="female") Then

MsgBox "You can retire at the age of 60" Else If (sex = "male") Then

MsgBox "You can retire at 65" Else

MsgBox " Error! You have entered an invalid sex." End If End Sub

Figure 6.4 Screenshot of Listing 6.4

Figure 6.4 Screenshot of Listing 6.4

0 0

Responses

  • heli
    What is a multiway if statement?
    7 years ago

Post a comment