VBScript If…Then If…Then…ElseIf If…Then…Else
VBScript If…Then If…Then…ElseIf If…Then…Else are also called conditional or logical statements. These statements help us in making a certain decision and perform appropriate actions.
In this article we will discuss these statements one by one with examples.
If…Then
This can be used if you want to do some action if the condition is true.
If store = open Then Buy something End If
Example:
On Error Resume Next Const a = 3 Const b = 3 Const c = 6 If a + b = c Then WScript.Echo(c) End If
Key points to note:
- If and the Then must be on same line.
- The action to be taken must be on the next line.
- You must you If…Then statement by End If.
- Make sure End If are two words.
If…Then…Else
This conditional statement makes you take decision on two points. First point when the condition is true and second point when the condition is false. Following example should make this clear.
If store = open Then Buy something Else Come back home End If
Example:
On Error Resume Next Const a = 3 Const b = 3 Const c = 6 If a + b = c Then WScript.Echo(c) Else WScript.Echo("Sum of a and d does not equal to 6") End If
If…Then…ElseIf
This conditional statement makes you take multiple decisions. You can have as many ElseIf as you need. You cant start with an If…Then and when you are finished add End If. Following information should make it clear-
If [condition] Then Do Something (1) ElseIf [condition] Then Do Something (2) Else Do Something (3) End If
Example:
On Error Resume Next Const a = 7 If a = 3 Then WScript.Echo("a is 3") ElseIf a = 4 Then WScript.Echo("a is 4") Else WScript.Echo("a is neither 3 nor 4") End If