The VBScript Network and Systems Administrator's Cafe

May 21 2008   6:49PM GMT

VBScript Statements: Explanation of If… Then … Endif

Jerry Lees Jerry Lees Profile: Jerry Lees

The If/Then/Else statement in VBScript is very similar to the Select Case statement, except it only normally allows for 2 possibilities in your condition.  Basically, the If/Then statement says– It is or it isn’t.

It very useful for testing a specific value to see if it is equal to, greater than, or less than something else and doing something based on the outcome of the condition. The statement always evaluates the expression based of if the condition is true. For example, this code would always run, because the condition would always be true:

x=1
if x=1 then
     ‘do something
Endif

While this code would never run:

x=1
if x>1 then
‘do something
endif

The else option is a useful tool as well, it applies to all other conditions should the if test expression(s) not be true. This allows for code to run under only certain situations, depending on the value of the expression:

x=1
if x=1 then
‘do something
else
‘do something else for all other possibilities

endif

Optionally, there is a elseif component of the statement that can include another condition. However, if you start to need more than more than one of these a select/case statement is likely a better option. Consider this example:


if x=1 then
‘do something
elseif x=0
‘ do something else
elseif x=2
‘ do another something else
elseif x=3
‘ do something completely different
else
‘do something else for all other possibilities
endif

In this last case, the important thing to remember is the only part of the code that runs is the where the expression best fits and only ONE section is executed.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: