VBScript If Else & ElseIf Statement in UFT | Excel

In VBScript, the If Else or elseif statement is used to write down decision-making statements. If the specified condition becomes true the code in the if block will be executed otherwise the code in the else block will be executed. We can use different types if statements based on the following scenarios.

  • If statement without an Else statement to execute a piece of code only when certain condition is met. The Else block is not required.
  • If Else statement to execute either of the blocks based on True and False condition
  • Nested If Else Statements to check multiple Boolean expressions.
  • We can also use If Else statement with combinations of Logical operator to evaluate Boolean expressions and inside a loop as well.

VBScript If Statement

The VBA If statement is used to execute a piece of code when the desired condition becomes True .The flow diagram of an if statement without else statement in VBScript is as follows.

vba-If-statement

The following is the syntax of an If Statement in VBScript.

If(Condition) Then
Statement 1
…..
…..
Statement n
End If

Example: Display output in message box only if value of variable a is greater than B

Output

vba-if-else-output

VBScript If Else Statement

The VBScript if else statement is used to execute either of the block statements based on the evaluation outcome (True or False) of the Boolean expression. The flow diagram of an If and Else statement in VBScript is as follows.

VBA If Else statement

The following is the syntax of an If Else Statement in VBScript.

If(Condition) Then
Statement 1
…..
…..
Statement n
Else
Statement 1
…..
…..
Statement n
End If

Example: Find which number is greater and display the output in the message box.

Output

vba-if-else-output

If you want to know more about user defined functions. Please refer User-Defined Functions

A bit more Complex If Else Statement Flow

vba-If-Else-statement-more-complex

Example: Find which number is greater and check whether the numbers lies between 1 to 9 or it is greater than 9.

Output

vba-if-else-statement-output-number-range

VBScript Nested If ElseIf Statement

Flow diagram of a nested If and Elseif Statement in VBScript is as follows. The ElseIf statement is used to evaluate a conditional statement only if the previous conditions have not been met.

vba-nested-If-Else-statement-complex

The following is the syntax of an nested If Elseif – Else statement in VBScript.

If(Condition 1) Then
Statement 1
…..
…..
Statement n
ElseIf (Condition 2) Then
Statement 1
…..
…..
Statement n
ElseIf (Condition 3) Then
Statement 1
…..
…..
Statement n
Else
Statement 1
…..
…..
Statement n
End If

Example: Display day name based on the input value between 1 to 7.

Output

Nested-if-else-vbscript

Conclusion

So in this article we have seen various uses of VBScript conditional if else Statements. I hope you might be able to use them wisely as per the need.

Recommended Posts

Leave a Reply