Conditional statements
Conditional statements are used to verify the conditions in the programming. On the basis of conditional statement, we can take actions like reporting the failure, moving to next step, stopping the execution etc.
We have following types of conditional statements.
1. If…Then
2. If…elseif..Then
3. else..
4. Nested If..else
5. Select statements
IF…Then: We can check the condition,on the basis of False or pass output of condition we can perform required statements. It should be enclosed with IF and End If statements.
If (condition)..Then
{Statement or a block of statement}
End if
Dim name name = "Shekhar" 'Condition will be true hence it will show message box Pass If name ="Shekhar" Then msgbox "Pass" End If
If …Elseif..Then: We use ‘elseif’ when we want to verify multiple condition.
If (condition)..Then
{Statement or a block of statement}
elseif (condition)..Then
{Statement or a block of statement}
End if
Dim name name = "Shekhar" If name ="Sharma" Then msgbox "Name is Sharma" ElseIf name = "Shekhar" Then msgbox "Name is shekhar" End If
We can put any no. of elseif into the code.
If..Else: If the condition in ‘If Then’ is not true, then control will go to the else part.
If (condition)..Then
{Statement or a block of statement}
else
{Statement or a block of statement}
End if
Dim name name = "Shekhar" If name ="Sharma" Then msgbox "Name is Sharma" Else msgbox "Name is shekhar" End If
Nested If: means that one If condition into another If condition.
Dim name,City name = "Shekhar" City = "bangalore" ' Nested if If name ="Shekhar" Then If City = "Delhi" Then msgbox "City is Delhi" Else msgbox "City is Bangalore" End If End If
Select Case Conditional statement: Suppose, we need to verify multiple conditions and we use ‘If..elseif’. Then, we have to put multiple elseif conditions. It is not a good practice to put so many elseif conditions. As a solution, we have another conditional statement called ‘Select case’ statements. It should be enclosed with ‘Select Case’ and ‘End Select’ statements.
Switch Case variable
Case VariableValue
{Statement or a block of statement}
Case VariableValue
{Statement or a block of statement}
Case else
{Statement or a block of statement}
Dnum=inputbox("enter the day number") Select case Dnum Case 1 Msgbox(“Sunday”) Case 2 Msgbox(“Monday”) Case 3 Msgbox(“Tuesday”) Case 4 Msgbox(“Wednesday”) Case 5 Msgbox(“Thursday”) Case 6 Msgbox(“Friday”) Case 7 Msgbox(“Saturday”) Case else Msgbox(“invalid number”) End select