Conditional statements


© Maxim Karetnikov

Conditional statements provide the capability to specify a statement or series of statements that only execute if the specified condition is True. For example, you could use a conditional statement to see if the user typed a numeric value in a field and, if they did, perform a mathematical calculation; but if they typed a string value, you would not want to perform the same calculation.

If…Then

The first and, probably, most widely used conditional statement is If…Then. The syntax for this control structure is given as

If condition = True Then
... the code that executes if the condition is satisfied 
End If 

where condition is some test you want to apply to the conditional structure. If the condition is true, the code within the If and End If statements is executed. If the condition is not true, the code within these statements is skipped over and does not  executed.

Suppose you have a Boolean variable named ShowPicture. This variable is set to True at some point in the code if the user wants to see the picture in the page or it set to False if he doesn't want.

If ShowPicture = True Then
...code that shows the picture
End If 

This way, if the user wants to see a picture the code in between the two statements is executed. Otherwise, the code is ignored.

If…Then…Else

Now you know how to make a simple decision in VBScript. The If…Then structure is useful, but it has one limitation. Oftentimes, when users make decisions, they want to do one thing if a condition is true; otherwise, they want to do something different. For example, one wants to see the picture of some process or to see the text giving a description of the process. Of cause, you can combine it from two If…Then statements in the following way:

 If ShowPicture = True Then
...code that shows the picture
End If
If ShowPicture = False Then
...code that displays the text
end if
 

But wouldn't it be better if you didn't have to repeat the test where you check the true or false condition?. Just for such cases, the If…Then…Else is used. Using it, one can rewrite the above code in more compact and cute way:

 If ShowPicture = True Then
...code that shows the picture

Go To Page: 1 2 3


The copyright of the article Conditional statements in VB Script is owned by . Permission to republish Conditional statements in print or online must be granted by the author in writing.

Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo