VBScript Conditionals
last modified February 19, 2025
In this article, we will learn how to use conditional statements in VBScript.
Conditionals allow you to execute different blocks of code based on certain
conditions. We will use WScript.Echo to output results and run the
scripts using cscript.
If Statement
The If statement is the simplest form of conditional.
Dim age
age = 20
If age >= 18 Then
WScript.Echo "You are an adult."
End If
This example checks if the value of age is greater than or equal to
18 and outputs a message if the condition is true.
If...Else Statement
The If...Else statement allows you to execute one block of code if
the condition is true and another if it is false.
Dim temperature
temperature = 25
If temperature < 20 Then
WScript.Echo "It's cold outside."
Else
WScript.Echo "It's warm outside."
End If
This example checks the value of temperature and outputs a message
based on the condition.
If...ElseIf...Else Statement
The If...ElseIf...Else statement allows you to check multiple
conditions.
Dim score
score = 85
If score >= 90 Then
WScript.Echo "Grade: A"
ElseIf score >= 80 Then
WScript.Echo "Grade: B"
ElseIf score >= 70 Then
WScript.Echo "Grade: C"
Else
WScript.Echo "Grade: D"
End If
This example checks the value of score and outputs a grade based on
the condition.
Select Case Statement
The Select Case statement is used to execute one of several blocks
of code based on the value of an expression.
Dim day
day = 3
Select Case day
Case 1
WScript.Echo "Monday"
Case 2
WScript.Echo "Tuesday"
Case 3
WScript.Echo "Wednesday"
Case Else
WScript.Echo "Invalid day"
End Select
This example checks the value of day and outputs the corresponding
day of the week.
Nested If Statements
You can nest If statements to check multiple conditions.
Dim x, y
x = 10
y = 20
If x > 5 Then
If y > 15 Then
WScript.Echo "Both conditions are true."
End If
End If
This example checks two conditions using nested If statements and
outputs a message if both conditions are true.
Logical Operators
VBScript supports logical operators like And, Or, and
Not to combine conditions.
Dim a, b
a = 5
b = 10
If a > 0 And b > 0 Then
WScript.Echo "Both numbers are positive."
End If
This example uses the And operator to check if both numbers are
positive.
In this article, we explored how to use conditional statements in VBScript. We
covered If, If...Else, If...ElseIf...Else,
Select Case, nested If statements, and logical
operators. Conditionals are essential for controlling the flow of your program
based on specific conditions.
Author
List all VBScript tutorials.