Introduction
1.Adding VBScript to Web Pages
Scripting languages, like JavaScript and VBScript, are
designed as an extension to HTML. The web browser receives scripts along with
the rest of the web document. It is the browser's responsibility to parse and
process the scripts. HTML was extended to include a tag that is used to
incorporate scripts into HTML-the <SCRIPT> tag.
The <SCRIPT> Tag
You add scripts into your web pages within a pair of
<SCRIPT> tags. The <SCRIPT> tag signifies the
start of the script section, while </SCRIPT> marks
the end. An example of this is shown below:
<HTML>
<HEAD>
<TITLE>Working With VBScript</TITLE>
<SCRIPT LANGUAGE="VBScript">
MsgBox "Welcome to my Web page!"
</SCRIPT>
You can use the SCRIPT element to add VBScript code to an HTML page.
The <SCRIPT> Tag
VBScript code is written within paired <SCRIPT> tags. For example, a
procedure to test a delivery date might appear as follows:
<SCRIPT LANGUAGE="VBScript">
<!--
Function CanDeliver(Dt)
CanDeliver = (CDate(Dt) - Now()) > 2
End Function
-->
</SCRIPT>
Beginning and ending <SCRIPT> tags surround the code. The LANGUAGE
attribute indicates the scripting language. You must specify the language
because browsers can use other scripting languages. Notice that the
CanDeliver function is embedded in
comment tags (<!-- and -->). This prevents browsers that don't understand the
<SCRIPT> tag from displaying the code.
Since the example is a general function—it isn't tied to any particular
form control—you can include it in the HEAD section of the page:
<HTML>
<HEAD>
<TITLE>Place Your Order</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Function CanDeliver(Dt)
CanDeliver = (CDate(Dt) - Now()) > 2
End Function
-->
</SCRIPT>
</HEAD>
<BODY>
...
You can use SCRIPT blocks anywhere in an HTML page. You can put them in
both the BODY and HEAD sections. However, you'll probably want to put all
general-purpose scripting code in the HEAD section in order to keep all the
code together. Keeping your code in the HEAD section ensures that all code is
read and decoded before it's needed by any calls from within the BODY section.
One notable exception to this rule is that you may want to provide inline
scripting code within forms to respond to the events of objects in your form.
For example, you can embed scripting code to respond to a button click in a
form:
<HTML>
<HEAD>
<TITLE>Test Button Events</TITLE>
</HEAD>
<BODY>
<FORM NAME="Form1">
<INPUT TYPE="Button" NAME="Button1" VALUE="Click">
<SCRIPT FOR="Button1" EVENT="onClick" LANGUAGE="VBScript">
MsgBox "Button Pressed!"
</SCRIPT>
</FORM>
</BODY>
</HTML>
Most of your code will appear in either Sub or Function
procedures and will be called only when code you have written causes it to
execute. However, you can write VBScript code outside procedures, but still
within a SCRIPT block. This code is executed only once, when the HTML page
loads. This allows you to initialize data or dynamically change the look of
your Web page when it loads.
Handling Non-Supporting Browsers
Not all browsers support scripting languages. Some only support JavaScript.
Only Microsoft's Internet Explorer supports VBScript. You might be wondering
what happens to your scripts when non-supporting browsers encounter them.
Usually browsers will do what they do most frequently with text, they will
display your scripts as part of the web page. Obviously, this isn't the result
you had hoped for. One simple way to address this problem is to encase your
scripts in comment tags (<!-- and
-->). Below is our example script as it appears with
the addition of the comment tags:
<HTML>
<HEAD>
<TITLE>Working With VBScript</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
MsgBox "Welcome to my Web page!"
-->
</SCRIPT>
</HEAD>
</HTML>
Now, when a browser that does not support VBScript processes this page, it
will view your script as a comment and simply ignore it.
Working with Variables
A variable is a named location in computer memory that you can use for
storage of data during the execution of your scripts. You can use variables to:
- Store input from the user gathered via your web page
- Save data returned from functions
- Hold results from calculations
An Introduction to Variables
Let's look at a simple VBScript example to clarify the use of variables.
Sub cmdVariables_OnClick
Dim Name
Name = InputBox("Enter your name: ")
MsgBox "The name you entered was " & Name
End Sub
The first line of this example defines a sub procedure associated with the
click event of a command button named cmdVariables.
On the second line we declare a variable named Name.
We are going to use this variable to store the name of the user when it is
entered. The third line uses the InputBox function
to first prompt for, and then return, the user's name. You will see more of the
InputBox function later in this tutorial. The name
it returns is stored in the Name variable.
The fourth line uses the MsgBox function to
display the user's name. Finally, the sub procedure completes on line five.
Exactly how, and where, variables are stored is not important. What you use
them for, and how you use them is important. That is what we will be looking at
next.
Declaring Variables
There are two methods for declaring variables in VBScript, explicitly and
implicitly. You usually declare variables explicitly with the
Dim statement:
Dim Name
This statement declares the variable Name. You
can also declare multiple variables on one line as shown below, although it is
preferable to declare each variable separately:
Dim Name, Address, City, State
Variables can be declared implicitly by simply using the variable name within
your script. This practice is not recommended. It leads to code that is prone to
errors and more difficult to debug.
You can force VBScript to require all variables to be explicitly declared by
including the statement Option
Explicit at the start of every script. Any variable
that is not explicitly declared will then generate an error.
Variable Naming Rules
When naming variables the following rules apply:
- They must begin with an alphabetic character
- They cannot contain embedded periods
- They must be unique within the same scope. There is more on
scopes later in this lesson
- They must be no longer than 255 characters
Variants and Subtypes
VBScript has a single data type called a variant.
Variants have the ability to store different types of data. The types of data
that a variant can store are referred to as subtypes.
The table below describes the subtypes supported by VBScript.
| Subtype |
Description of Uses for Each Subtype |
| Byte |
Integer numbers between 0 to 255 |
| Boolean |
True and False |
| Currency |
Monetary values |
| Date |
Date and time |
| Double |
Extremely large numbers with decimal points |
| Empty |
The value that a variant holds before being used |
| Error |
An error number |
| Integer |
Large integers between -32,768 and 32,767 |
| Long |
Extremely large integers (-2,147,483,648 and 2,147,483,647) |
| Object |
Objects |
| Null |
No valid data |
| Single |
Large numbers with decimal points |
| String |
Character strings |
What Are VBScript Data Types?
VBScript has only one data type called a Variant. A Variant
is a special kind of data type that can contain different kinds of
information, depending on how it's used. Because Variant is the only
data type in VBScript, it's also the data type returned by all functions in
VBScript.
At its simplest, a Variant can contain either numeric or string
information. A Variant behaves as a number when you use it in a numeric
context and as a string when you use it in a string context. That is, if
you're working with data that looks like numbers, VBScript assumes that it is
numbers and does the thing that is most appropriate for numbers. Similarly, if
you're working with data that can only be string data, VBScript treats it as
string data. Of course, you can always make numbers behave as strings by
enclosing them in quotation marks (" ").
Variant Subtypes
Beyond the simple numeric or string classifications, a Variant can
make further distinctions about the specific nature of numeric information.
For example, you can have numeric information that represents a date or a
time. When used with other date or time data, the result is always expressed
as a date or a time. Of course, you can also have a rich variety of numeric
information ranging in size from Boolean values to huge floating-point
numbers. These different categories of information that can be contained in a
Variant are called subtypes. Most of the time, you can just put the
kind of data you want in a Variant, and the Variant behaves in a
way that is most appropriate for the data it contains.
The following table shows the subtypes of data that a Variant can
contain.
| Subtype |
Description |
| Empty |
Variant is uninitialized. Value is 0 for numeric
variables or a zero-length string ("") for string variables. |
| Null |
Variant intentionally contains no valid data.
|
| Boolean |
Contains either
True or
False. |
| Byte |
Contains integer in the range 0 to 255. |
| Integer |
Contains integer in the range -32,768 to 32,767.
|
| Currency |
-922,337,203,685,477.5808 to 922,337,203,685,477.5807. |
| Long |
Contains integer in the range -2,147,483,648 to
2,147,483,647. |
| Single |
Contains a single-precision, floating-point number in
the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45
to 3.402823E38 for positive values. |
| Double |
Contains a double-precision, floating-point number in
the range -1.79769313486232E308 to -4.94065645841247E-324 for negative
values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. |
| Date (Time) |
Contains a number that represents a date between
January 1, 100 to December 31, 9999. |
| String |
Contains a variable-length string that can be up to
approximately 2 billion characters in length. |
| Object |
Contains an object. |
| Error |
Contains an error number. |
You can use
conversion functions to convert data from one subtype to another. In
addition, the
VarType function returns information about how your data is stored
within a Variant.
Assigning Values
You assign a value to a variable by using the following format:
Variable_name = value
The following examples demonstrate assigning values to variables:
Name = "Larry Roof"
HoursWorked = 50
Overtime = True
Scope of Variables
The scope of a variable dictates where it can be used in your script. A
variable's scope is determined by where it is declared. If it is declared within
a procedure, it is referred to as a procedure-level
variable and can only be used within that procedure. If it is declared outside
of any procedure, it is a script-level variable
and can be used throughout the script.
The example below demonstrates both script-level and procedure-level
variables.
<SCRIPT>
Dim counter
Sub cmdButton_onClick
Dim temp
End Sub
</SCRIPT>
The variable counter is a script-level variable
and can be utilized throughout the script. The variable
temp exists only within the cmdButton_onClick
sub-procedure.
Constants
What Is a Constant?
A
constant is a meaningful name that takes the place of a number or string
and never changes. VBScript defines a number of
intrinsic constants. You can get information about these intrinsic
constants from the
VBScript Language Reference.
Creating Constants
You create user-defined constants in VBScript using the
Const statement. Using the Const statement, you can create
string or numeric constants with meaningful names and assign them literal
values. For example:
Const MyString = "This is my string."
Const MyAge = 49
Note that the string literal is enclosed in quotation marks (" ").
Quotation marks are the most obvious way to differentiate string values from
numeric values.
Date literals and time literals are represented by enclosing them in
number signs (#). For example:
Const CutoffDate = #6-1-97#
You may want to adopt a naming scheme to differentiate constants from
variables. This will prevent you from trying to reassign constant values while
your script is running. For example, you might want to use a "vb" or "con"
prefix on your constant names, or you might name your constants in all capital
letters. Differentiating constants from variables eliminates confusion as you
develop more complex scripts.
Arrays
The VBScript language provides support for arrays. You declare an array using
the Dim statement, just as you did with variables:
Dim States(50)
The statement above creates an array with 51 elements. Why 51? Because
VBScript arrays are zero-based, meaning that the
first array element is indexed 0 and the last is the number specified when
declaring the array.
You assign values to the elements of an array just as you would a variable,
but with an additional reference (the index) to the element in which it will be
stored:
States(5) = "California"
States(6) = "New York"
Arrays can have multiple dimensions-VBScript supports up to 60. Declaring a
two dimensional array for storing 51 states and their capitals could be done as
follows:
Dim StateInfo(50,1)
To store values into this array you would then reference both dimensions.
StateInfo(18,0) = "Michigan"
StateInfo(18,1) = "Lansing"
VBScript also provides support for arrays whose size may need to change as
the script is executing. These arrays are referred to as
dynamic arrays.
A dynamic array is declared without specifying the number of elements it will
contain:
Dim Customers()
The ReDim statement is then used to change the
size of the array from within the script:
ReDim Customers(100)
There is no limit to the number of times an array can be re-dimensioned
during the execution of a script. To preserve the contents of an array when you
are re-dimensioning, use the Preserve keyword:
ReDim Preserve Customers(100) .