Conditional
Conditional Statements in VBScript
Β
Conditional statements are used to make decisions in a program. Based on whether a condition is true or false, different blocks of code are executed.
VBScript provides the following four conditional statements:
If statement β Executes code when a condition is true
Ifβ¦Thenβ¦Else statement β Chooses between two blocks of code
Ifβ¦Thenβ¦ElseIf statement β Selects one block from multiple conditions
Select Case statement β Executes one block from several possible options
Ifβ¦Thenβ¦Else Statement
Β
Use the Ifβ¦Thenβ¦Else statement when you want to run code only when a condition is satisfied or choose between two alternatives.
Single-Line If Statement
If only one statement needs to be executed when the condition is true, it can be written on a single line:
Β
If i = 10 Then Response.Write("Hello")
In this case, the statement executes only when i equals 10. There is no Else part here.
Multi-Line If Statement
Β
When more than one statement needs to be executed, the code must be written on separate lines and closed with End If:
Β
If i = 10 Then Β Response.Write("Hello") Β i = i + 1 End If
This code runs all the statements inside the block if the condition is true.
Ifβ¦Thenβ¦Else Example
Β
To execute one block when the condition is true and another block when it is false, use Else:
Β
i = Hour(Time) If i < 10 Then Β Response.Write("Good morning!") Else Β Response.Write("Have a nice day!") End If
Here, the first message is displayed if the time is before 10, otherwise the second message is shown.
Ifβ¦Thenβ¦ElseIf Statement
Β
When multiple conditions need to be checked, the ElseIf keyword can be used:
Β
i = Hour(Time) If i = 10 Then Β Response.Write("Just started...!") ElseIf i = 11 Then Β Response.Write("Hungry!") ElseIf i = 12 Then Β Response.Write("Ah, lunch-time!") ElseIf i = 16 Then Β Response.Write("Time to go home!") Else Β Response.Write("Unknown") End If
Each condition is evaluated in order, and the block associated with the first true condition is executed.
Select Case Statement
Β
The Select Case statement is another way to choose one block of code from multiple options. It is often clearer than using many ElseIf statements.
Example:
Β
d = Weekday(Date) Select Case d Β Case 1 Β Β Β Response.Write("Sleepy Sunday") Β Case 2 Β Β Β Response.Write("Monday again!") Β Case 3 Β Β Β Response.Write("Just Tuesday!") Β Case 4 Β Β Β Response.Write("Wednesday!") Β Case 5 Β Β Β Response.Write("Thursday...") Β Case 6 Β Β Β Response.Write("Finally Friday!") Β Case Else Β Β Β Response.Write("Super Saturday!!!!") End Select
How Select Case Works
Β
A single expression (usually a variable) is evaluated once
Its value is compared against each Case
When a match is found, the corresponding block of code is executed
If no case matches, the Case Else block runs