If Then archives - The VBScript Network and Systems Administrator's Cafe

The VBScript Network and Systems Administrator's Cafe:

If Then

May 21 2008   6:49PM GMT

VBScript Statements: Explanation of If… Then … Endif



Posted by: Jerry Lees
VBScript, Logical File, VBScript Statements, vbscriptstatements, Then, else, IF Then Else, If Then

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.