About Me

Saturday 21 April 2012

VBScript If Statement

VBScript If Statement

One of the most common programming tools that is required to write any kind of program is the If Statement. This lesson will give you the basic rundown of how to implement an If Statement in VBScript.

Making decisions is a tiring process, so it's nice to know that you can make your program make decisions for you if you tell it what it needs to pay attention to. An If Statement is a mechanism programmers have been using for quite some time that will execute a block of code IF conditions are true.
For example, you may want to print out "Is someone having a case of the Mondays?" on your web site every Monday morning. Your If Statement would check to see if the day was a Monday and if it was (true) then it would execute the code to print out that annoying line of text.

VBScript If Statement: Syntax

In this lesson we will be creating a simple VBScript If Statement that checks to see if a number stored in the variable myNumber is equal to 7. If this is true then it will execute a document.write function to print some text to the browser.

VBScript Code:

<script type="text/vbscript">
Dim myNumber
myNumber = 7
If myNumber = 7 Then
 document.write("Lucky 7!")
End If
myNumber = 100343
If myNumber = 7 Then
 document.write("You're a winner!")
End If

</script>

Display:

Lucky 7!
This example show that in our first If Statement myNumber is indeed equal to 7 and the block of code that prints out "Lucky 7!" is executed. However, we then set myNumber equal to something that is not 7 (100343) and check with a second If Statement and the block of code that should print out "You're a winner!" is not executed.
The code that resides within an if statement is only executed if the condition statement of that If Statement is True.

VBScript If Statement: Else

Sometimes you would like to have code executed with something is true and when something is false. For example, if you wanted to wear a T-shirt if the temperature was above 70 and a long-sleeved shirt if it was 70 or less. This action to be taken if the conditional statement is false (that is, the temperature is not above 70 degrees) is referred to in programming speak as the Else clause of the If Statement.
If something is true I want to do Code A, Else I want to do Code B.Below is the implementation of our "what shirt to wear" problem.

VBScript Code:

<script type="text/vbscript">
Dim temperature
temperature = 50
If temperature > 70 Then
 document.write("Wear a T-Shirt!")
Else 
 document.write("Wear a long-sleeved shirt!")
End If


</script>

Display:

Wear a long-sleeved shirt!

0 comments:

Post a Comment