Monday 10 February 2014

VBScript Variables


VBScript Variables
VBScript variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carname.
Rules for VBScript variable names:
    Must begin with a letter
    Cannot contain a period (.)
    Cannot exceed 255 characters

In VBScript, all variables are of type variant that can store different types of data.
Declaring (Creating) VBScript Variables

Creating variables in VBScript is most often referred to as "declaring" variables.

You can declare VBScript variables with the Dim, Public or the Private statement. Like this:
Dim x
Dim carname

Now you have created two variables. The name of the variables are "x" and "carname".

You can also declare variables by using its name in a script. Like this:
carname="orange"

Now you have also created a variable. The name of the variable is "carname". However, this method is not a good practice, because you can misspell the variable name later in your script, and that can cause strange results when your script is running.
If you misspell for example the "carname" variable to "carnime", the script will automatically create a new variable called "carnime".  To prevent your script from doing this, you can use the Option Explicit statement. This statement forces you to declare all your variables with the dim, public or private statement.
Put the Option Explicit statement on the top of your script. Like this:
Option Explicit
Dim carname
carname=some value
You assign a value to a variable like this:
carname="orange"
x=10
The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the variable "carname" has the value of "orange", and the variable "x" has the value of "10".

When you declare a variable within a procedure, the variable can only be accessed within that procedure. When the procedure exits, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different procedures, because each is recognized only by the procedure in which it is declared.

If you declare a variable outside a procedure, all the procedures on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.

No comments:

Post a Comment