If..Then - VBScript
Overview
The If..Then command in VBScript is used for conditional execution, allowing you to execute specific code blocks only if certain conditions are met. It is essential for controlling the flow of your scripts and making decisions based on user input or other dynamic factors.
Syntax
If expression Then
' Code to execute if expression is True
ElseIf expression2 Then
' Code to execute if expression2 is True
Else
' Code to execute if neither expression is True
End If
Parameters:
- expression, expression2: Boolean expressions that evaluate to
TrueorFalse.
Options/Flags
None.
Examples
Simple example:
If age > 18 Then
Print "You are eligible to vote"
Else
Print "You are not eligible to vote"
End If
Complex example:
Dim username, password
' Prompt user for username and password
username = InputBox("Enter your username:")
password = InputBox("Enter your password:")
If username = "admin" And password = "secret" Then
Print "Welcome, administrator"
' Execute admin-level code
ElseIf username = "user" And password = "letmein" Then
Print "Welcome, user"
' Execute user-level code
Else
Print "Invalid credentials"
End If
Common Issues
- Incorrect syntax: Ensure that your
If..Thenstatement has a matchingEnd Ifto avoid syntax errors. - Invalid expressions: Expressions must evaluate to
TrueorFalse. Avoid using expressions that result in non-Boolean values.
Integration
If..Then can be combined with other VBScript commands like ElseIf and Select Case for more complex conditional logic. It can also be used with Do..While and For..Next loops for iterative execution.
Related Commands
Select Case– Another conditional statement for more complex branching.Do..While– Iterative loop that executes while a condition isTrue.For..Next– Iterative loop that executes a specified number of times.