Declaring variables in ASP is simple, especially since all variables are of Variant type. What does this mean to you? You don’t have to declare if your variable is an integer, string, or object. You just declare it, and it has the potential to be anything. To declare a variable in ASP/VBScript we use the Dim statement. If you wanted to print out the variables, you could use the ASP ‘Response.Write’ command.
Here is some code creating and assigning values to a couple of variables:
<%@ LANGUAGE="VBSCRIPT" %>
<%
'Commented lines starting with an apostrophe
'are not executed in VBScript
'First we will declare a few variables.
Dim myText, myNum
'To declare a variable, you just put the
'word Dim in front of the variable name.
'Let's assign a value to these
myText = "Have a nice day!"
myNum = 5
'Note that myText is a string and myNum is numeric.
'Next we will display these to the user.
Response.Write(myText)
'To concatenate strings in VBScript, use the ampersand
Response.Write(" My favourite number is " & myNum)
%>
The output is: Have a nice day! My favourite number is 5.
In ASP/VBScript, it is possible not to declare variables at all. A variable can appear in the program, though it has never been declared. It is called default declaring. Variable in this case will be of Variant type.
However, such practice leads to errors and should be avoided. For VB to consider any form or module variable that was not declared explicitly as erroneous, Option Explicit statement should appear in the form or module main section before any other statements. Option Explicit demands explicit declaration of all variables in this form or module. If module contains Option Explicit statement, than upon the attempt to use undeclared or incorrectly typed variable name, an error occurs at compile time.
In naming variables in VBScript you must be aware of these rules:
- Variables must begin with a letter not a number or an underscore
- They cannot have more than 255 characters
- They cannot contain a period (.) , a space or a dash
- They cannot be a predefined identifier (such as dim, variable, if, etc.)
- Case sensitivity is not important in VBScript
The variable value will be kept in memory for the life span of the current page and will be released from memory when the page has finished executing. To declare variables accessible to more than one ASP file, declare them as session variables or application variables.