Using Visual Basic Scripting Edition in HTML

Microsoft Corporation

September 1996

Contents

What Is VBScript?

What VBScript Looks Like in HTML

VBScript Basics

Using VBScript in Internet Explorer 3.0

Appendix: Conversion Functions

What Is Visual Basic Scripting Edition?

Summary

Here you'll find a description of Microsoft® Visual Basic® Scripting Edition (VBScript), and an overview of the Visual Basic product line. In this article, you'll first see what VBScript looks like when it's inside a Hypertext Markup Language (HTML) page. You'll learn about variables, constants, and procedures. Then you'll see how to use VBScript to handle standard HTML form controls and to validate data. Finally, you'll see how to extend the power of your pages with ActiveX™ controls (formerly called OLE Controls) and other objects.

VBScript

VBScript, the newest member of the Microsoft Visual Basic family of programming languages, brings active scripting to the Web. Microsoft Internet Explorer version 3.0 can read VBScript programs embedded in HTML pages. With VBScript, you can validate form data, automatically generate custom pages, or even write games—all from inside your Web pages and without server-side programming.

Easy to Use and Learn

If you already know Visual Basic or Visual Basic for Applications, VBScript will be very familiar. Even if you don't know Visual Basic, once you learn it you're on your way to programming with the whole family of Visual Basic languages.

Although this article will teach you about VBScript, it won't teach you how to program. To get started programming, take a look at Microsoft Visual Basic 4 Step by Step by Michael Halvorson, available from Microsoft Press.

ActiveX Scripting

VBScript talks to host applications using Microsoft ActiveX scripting. ActiveX scripting prevents browsers and other host applications from needing to write special integration code for each scripting component. ActiveX scripting enables a host to compile scripts, obtain and call entry points, and manage the namespace available to the developer. With ActiveX scripting, language vendors can create standard language run times for scripting. Microsoft will provide runtime support for VBScript and Visual Basic. Microsoft is working with various Internet groups to define the ActiveX scripting standard so that scripting engines can be interchangeable. ActiveX scripting is used in Microsoft Internet Explorer 3.0.

VBScript in Other Applications and Browsers

As a developer, you may license the VBScript source implementation at no charge for use in your products. Microsoft provided binary implementations of VBScript for the 32-bit Microsoft Windows® application programming interface (API), the 16-bit Windows API, and the Apple® Macintosh® in 1996. VBScript is integrated with World Wide Web browsers and is designed to work with ActiveX controls and other objects embedded in active HTML documents. VBScript and ActiveX scripting, can, however, also be used as a general scripting language in other applications.

The Visual Basic Product Line

Microsoft has designed Visual Basic as a scalable development tool for a range of applications, including Internet and enterprise applications. Visual Basic can be used to create active HTML documents, customize productivity products, and build client/server business applications.

Figure 1. The Microsoft Visual Basic family

To support a full range of applications, Microsoft provides Visual Basic in three upwardly compatible packages:

VBScript

This lightweight subset of the Microsoft Visual Basic programming language will be licensed to corporations free of charge. Microsoft will provide VBScript for the Windows and Macintosh operating systems, and is working with third parties to provide Unix versions for Sun, Hewlett-Packard, Digital, and IBM platforms. VBScript is packaged as a compiler and associated runtime libraries. Microsoft does not currently provide integrated development support tools (such as editing, layout, and debugging tools) for VBScript. VBScript became available to licensees and other interested parties in 1996.

Visual Basic for Applications

Visual Basic for Applications is Microsoft's strategic application scripting language. This highly extensible language uses Automation (formerly OLE Automation) and program objects. Visual Basic for Applications provides a complete development environment, including integrated editor and debugging support. Visual Basic for Applications is currently available only with the Microsoft Office family of products for the Windows and Macintosh operating systems.

Visual Basic Version 4.0

The Visual Basic development tool is available in three editions: the Standard Edition for students and hobbyists, the Professional Edition for individual developers, and the Enterprise Edition for developer teams or corporate development. Visual Basic version 4.0 provides a superset of the language and tool functionality found in Visual Basic for Applications. The key features of the Enterprise Edition product include remote client/server data access, distributed computing support (for example, for three-tiered architectures), and team source code control support. Visual Basic 4.0 is currently available only for the Windows operating system.

What VBScript Looks Like in HTML

The <SCRIPT> Tag

In an HTML page, VBScript code goes inside 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. Notice that the LANGUAGE attribute indicates the scripting language. You need to specify the language since Microsoft Internet Explorer 3.0 can use other scripting languages. In addition, 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 procedures in code anywhere in a page. You can put procedures in both the BODY and HEAD sections. However, you may want to put all procedures in the HEAD section in order to keep all the code together.

Now, let's look at some elements of the language.

VBScript Basics

VBScript Data Types

What are the VBScript data types?

VBScript has only one data type and it's 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're using 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. Of course, you can always make numbers behave as strings, by enclosing them in quotation marks. Similarly, if you're working with data that can only be string data, VBScript treats it as string data.

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 it behaves in a way that is most appropriate for the data it contains.

Table 1 shows the various subtypes of data that a Variant can contain.

Table 1. Possible Data Subtypes for a Variant

Subtype Meaning
Empty Variant is uninitialized. Value is either 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 an integer in the range 0 to 255.
Integer Contains an integer in the range -32,768 to 32,767.
Long Contains an integer in the range -2,147,483,648 to 2,147,483,647. SingleContains 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. StringContains a variable-length string that can be up to approximately 2 billion characters in length.
Object Contains an object.
Error Contains an error number.

If you want to convert from one subtype to another, there is a rich set of conversion functions you can use (see Appendix). In addition, another function, VarType, returns information about how your data is stored within a Variant.

VBScript Variables

What is a variable?

A variable is a convenient placeholder that refers to a computer memory location where you can store program information that may change during the time your script is running. For example, you might create a variable called ClickCount to store the number of times a user clicked an object on a particular Web page. Where the variable is located in computer memory is unimportant. What's important is that you only have to refer to it by name to see its value or to change its value. In VBScript, variables are always of one fundamental data type, Variant.

Declaring variables

You declare variables explicitly in your script using the Dim statement. For example:

<SCRIPT LANGUAGE="VBScript">
<!--
 Dim DegreesFahrenheit
-->
</SCRIPT>
You declare multiple variables by separating each variable name with a comma. For example:
<SCRIPT LANGUAGE="VBScript">
<!--
 Dim Top, Bottom, Left, Right
-->
</SCRIPT>

You can also declare a variable implicitly by simply using its name somewhere in your script. That's not generally considered to be a good practice because you could misspell the variable name in one or more places, causing unexpected results when your script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables. The Option Explicit statement should be the first statement inside your <SCRIPT> tag.

Naming restrictions

Variable names follow the standard rules for naming anything in VBScript. A variable name:

Limit on number of variables

When using variables in VBScript these limitations apply:

Scope and lifetime of variables

Generally, when you declare a variable within a procedure, only code within that procedure can access or change the value of that variable; it has local scope and is known as a procedure-level variable. Sometimes, however, you need to use a variable with a broader scope, such as one whose value is available to all the procedures within the same script. If you declare a variable outside a procedure, you make it recognizable to all the procedures in your script. This kind of script-level variable is said to have script-level scope.

The length of time a variable exists is its lifetime. A script-level variable's lifetime extends from the time it is declared until the time the script is finished running. A local variable's lifetime begins when its declaration statement is encountered as the procedure begins, and ends when the procedure concludes. Local variables are ideal as temporary storage space when a procedure is executing. You can have local variables of the same name in several different procedures because each is recognized only by the procedure in which it is declared.

A variable's scope is determined by where you declare it. At script level, the lifetime of a variable is always the same. It exists for as long as the script is running. At procedure level, a variable exists only so long as you are in the procedure. When the procedure exits, the variable is destroyed.

Assigning values to variables

Values are assigned to variables with an expression such that the variable is on the left side of the expression and the value you want to assign to the variable is on the right. For example:

<SCRIPT LANGUAGE="VBScript">
<!--
 B = 200
-->
</SCRIPT>

Scalars and arrays

Much of the time, you only want to assign a single value to a variable you've declared. A variable containing a single value is a scalar variable. Other times, it's convenient to assign more than one related value to a single variable. Then you can create a variable that can contain a series of values. This is called an array variable. Array variables are declared much the same way as scalar variables. The difference is that a declaration of an array variable uses parentheses following the variable name. In the following example, a single-dimension array containing 11 elements is declared:

<SCRIPT LANGUAGE="VBScript">
<!--
 Dim A(10)
-->
</SCRIPT>

Although the number shown in the parentheses is 10, all arrays in VBScript are zero-based, so this array actually contains 11 elements. In a zero-based array, the number of array elements is always the number shown in parentheses plus one. This kind of an array is called a fixed-size array.

You assign data to each of the elements of the array using an index into the array. Beginning at zero and ending at 10, data can be assigned to the elements of an array as follows:

<SCRIPT LANGUAGE="VBScript">
<!--
 A(0) = 256
 A(1) = 324
 A(2) = 100
 . . .
 A(10) = 55
-->
</SCRIPT>

Similarly, the data can be retrieved from any element using an index into the particular array element you want. For example:

<SCRIPT LANGUAGE="VBScript">
<!--
 . . .
 SomeVariable = A(8)
 . . .
-->
</SCRIPT>

Arrays aren't limited to a single dimension. You can have as many as 60 dimensions, although most people can't comprehend more than about three or four. Multiple dimensions are declared by separating an array's size numbers in the parentheses with commas. In the following example, the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns:

<SCRIPT LANGUAGE="VB">
<!--
 Dim MyTable(5, 10)
-->
</SCRIPT>

In a two-dimensional array, the first number is always the number of rows; the second the number of columns.

You can also declare an array whose size changes during the time your script is running. This is called a dynamic array. The array is initially declared within a procedure using either the Dim statement, as with any other array, or the ReDim statement. The difference is that no size or number of dimensions is placed inside the parentheses. For example:

<SCRIPT LANGUAGE="VBScript">
<!--
 Dim MyArray()
 ReDim AnotherArray()
-->
</SCRIPT>

To use a dynamic array, you must subsequently use ReDim to determine the number of dimensions and the size of each. In the following example, ReDim sets the initial size of the dynamic array to 25. A subsequent ReDim statement resizes the array to 30, but uses the Preserve keyword to preserve the contents of the array as the resizing takes place.

<SCRIPT LANGUAGE="VBScript">
<!--
 ReDim MyArray(25)
 . . .
 ReDim Preserve MyArray(30)
-->
</SCRIPT>

There is no limit to the number of times you can resize a dynamic array, but you should know that if you make an array smaller than it was, you lose the data in the eliminated elements.

VBScript Constants

What is a constant?

A constant is a meaningful name that takes the place of a number or string and never changes. VBScript currently has no constants defined by the language. In VBScript, constants are implemented as literal values assigned to variable names.

Creating constants

You create constants in VBScript the same way you declare variables, using the Dim statement. Using the Dim statement, you can create string or numeric constants with meaningful names. You can then assign them literal values and use them in your script. For example:

Dim MyString
MyString = "This is my string."
Dim MyAge
MyAge = 49

Note that the string literal is enclosed in quotation marks ("). Quotation marks are the best, most obvious way to differentiate string values from numeric values. Date/time literals can be represented by enclosing them in number signs (#). For example:

Dim CutoffDate
CutOffDate = #12-21-96#

Since there is no functional difference between constants created in this way and regular variables, you may want to adopt a naming scheme to differentiate constants from variables. This will prevent you from trying to reassign their values while your script is running. For example, you might want to use a "vb" prefix on your constant names, or you may want to use all capital letters in your constants' names as recommended in VBScript Coding Conventions. In either case, it is a good idea to differentiate constants from variables. This eliminates confusion as you develop more complex scripts.

VBScript Operators

Operator precedence

VBScript has a full range of operators, including arithmetic operators, comparison operators, concatenation operators, and logical operators.

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order. That order is known as operator precedence. You can use parentheses to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, normal operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left to right order in which they appear. Arithmetic and logical operators are evaluated in the order of precedence, from top to bottom, as shown below.

Table 2. VBScript Operators

Arithmetic Comparison Logical
Description Symbol Description Symbol Description Symbol
Exponentiation ^ Equality = Logical negation Not
Unary negation - Inequality <> Logical conjunction And
Multiplication * Less than < Logical disjunction Or
Division / Greater than > Logical exclusion Xor
Integer division \ Less than or equal to <= Logical equivalence Eqv
Modulo arithmetic Mod Greater than or equal to >= Logical implication Imp
Addition + Object equivalence Is
Subtraction -
String concatenation &

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right.

The string concatenation operator (&) is not an arithmetic operator, but in precedence it does fall after all arithmetic operators and before all comparison operators. The Is operator is an object reference comparison operator. It does not compare objects or their values; it checks only to determine if two object references refer to the same object.

Controlling Program Flow in VBScript

Controlling program execution

Using conditional statements and looping statements (also known as control structures), you can write VBScript code that makes decisions and repeats actions.

Making decisions using If...Then...Else

The If...Then...Else statement is used to evaluate whether a condition is True or False, and then to specify one or more statements to run, depending on the result. Usually, the condition is an expression that uses a comparison operator to compare one value or variable with another. For information about comparison operators, see "Comparison Operators" in the Visual Basic documentation in the MSDN Library. If...Then...Else statements can be nested to as many levels as you need.

Running statements if a condition is true

If you need to run only one statement when a condition is True, you can use the single-line syntax of the If...Then...Else statement. The following example shows the single-line syntax; notice that this example omits the Else keyword.

<SCRIPT LANGUAGE="VBScript">
<!--
 Sub FixDate()
     Dim myDate
     myDate = #2/13/95#
     If myDate < Now Then myDate = Now
 End Sub
-->
</SCRIPT>

If you want to run more than one line of code, you must use the multiple-line syntax. This syntax includes the End If statement, as shown in the following example:

<SCRIPT LANGUAGE="VBScript">
<!--
 Sub AlertUser(value)
     If value = 0 Then
         AlertLabel.ForeColor = "Red"
         AlertLabel.Font.Bold = True
         AlertLabel.Font.Italic = True
     End If
 End Sub
-->
</SCRIPT>

Running certain statements if a condition is True, and running others if it is False

You can use an If...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the condition is False.

<SCRIPT LANGUAGE="VBScript">
<!--
 Sub AlertUser(value)
     If value = 0 Then
         AlertLabel.ForeColor = vbRed
         AlertLabel.Font.Bold = True
         AlertLabel.Font.Italic = True
     Else
         AlertLabel.Forecolor = vbBlack
         AlertLabel.Font.Bold = False
         AlertLabel.Font.Italic = False
     End If
 End Sub
-->
</SCRIPT>

Using loops to repeat code

Looping allows you to run a group of statements repeatedly. Some loops repeat statements until a condition is False, others repeat statements until a condition is True. There are also loops that repeat statements a specific number of times.

The following looping statements are available in VBScript:

Using Do Loops

You can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True.

Repeating statements while a condition is True

Use the While keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the first Sub procedure following this paragraph), or you can check it after the loop has run at least once (as shown in the second Sub procedure). In the ChkFirstWhile procedure, if myNum were set to 9 instead of 20, the statements inside the loop would never run. In the ChkLastWhile procedure, the statements inside the loop run only once because the condition is already False.

<SCRIPT LANGUAGE="VBScript">
<!--
 Sub ChkFirstWhile()
     Dim counter, myNum
     counter = 0
     myNum = 20
     Do While myNum > 10
         myNum = myNum - 1
         counter = counter + 1
     Loop
     MsgBox "The loop made " & counter & " repetitions."
 End Sub
 Sub ChkLastWhile()
     Dim counter, myNum
     counter = 0
     myNum = 9
     Do
         myNum = myNum - 1
         counter = counter + 1
     Loop While myNum > 10
     MsgBox "The loop made " & counter & " repetitions."
 End Sub
-->
</SCRIPT>

Repeating a statement until a condition becomes True

You can use the Until keyword in two ways to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the first Sub procedure following this paragraph), or you can check it after the loop has run at least once (as shown in the second Sub procedure). As long as the condition is False, the looping occurs.

<SCRIPT LANGUAGE="VBScript">
<!--
 Sub ChkFirstUntil()
     Dim counter, myNum
     counter = 0
     myNum = 20
     Do Until myNum = 10
         myNum = myNum - 1
         counter = counter + 1
     Loop
     MsgBox "The loop made " & counter & " repetitions."
 End Sub
 Sub ChkLastUntil()
     Dim counter, myNum
     counter = 0
     myNum = 1
     Do
         myNum = myNum + 1
         counter = counter + 1
     Loop Until myNum = 10
     MsgBox "The loop made " & counter & " repetitions."
 End Sub
-->
</SCRIPT>

Exiting a Do...Loop statement from inside the loop

You can exit a Do...Loop statement by using the Exit Do statement. Because you usually want to exit only in certain situations, such as to avoid an endless loop, you should use the Exit Do statement in the True statement block of an If...Then...Else statement. If the condition is False, the loop runs as usual.

In the following example, myNum is assigned a value that creates an endless loop. The If...Then...Else statement checks for this condition, preventing the endless repetition.

<SCRIPT LANGUAGE="VB">
<!--
 Sub ExitExample()
     Dim counter, myNum
     counter = 0
     myNum = 9
     Do Until myNum = 10
         myNum = myNum - 1
         counter = counter + 1
         If myNum < 10 Then Exit Do
     Loop
     MsgBox "The loop made " & counter & " repetitions."
 End Sub
-->
</SCRIPT>

Using While...Wend

The While...Wend statement is provided in VBScript for those who are familiar with its usage. However, because of the lack of flexibility in While...Wend, it is recommended that you use the Do...Loop statement instead.

Using For...Next

You can use For...Next statements to run a block of statements a specific number of times. For loops, use a counter variable whose value is increased or decreased with each repetition of the loop.

For example, the following procedure causes a procedure called MyProc to execute 50 times. The For statement specifies the counter variable x and its start and end values. The Next statement increments the counter variable by 1.

<SCRIPT LANGUAGE="VBScript">
<!--
 Sub DoMyProc50Times()
     Dim x
     For x = 1 To 50
         MyProc
     Next
 End Sub
-->
</SCRIPT>

Using the Step keyword, you can increase or decrease the counter variable by the value you specify. In the following example, the counter variable j is incremented by 2 each time the loop repeats. When the loop is finished, the total is the sum of 2, 4, 6, 8, and 10.

<SCRIPT LANGUAGE="VBScript">
<!--
 Sub TwosTotal()
     Dim j, total
     For j = 2 To 10 Step 2
         total = total + j
     Next
     MsgBox "The total is " & total
 End Sub
-->
</SCRIPT>

To decrease the counter variable, you use a negative Step value. When doing so, you must specify an end value that is less than the start value. In the following example, the counter variable myNum is decreased by 2 each time the loop repeats. When the loop is finished, the total is the sum of 16, 14, 12, 10, 8, 6, 4, and 2.

<SCRIPT LANGUAGE="VBScript">
<!--
 Sub NewTotal()
     Dim myNum, total
     For myNum = 16 To 2 Step -2
         total = total + myNum
     Next
     MsgBox "The total is " & total
 End Sub
-->
</SCRIPT>

You can exit any For...Next statement before the counter reaches its end value by using the Exit For statement. Because you usually want to exit only in certain situations, such as when an error occurs, you should use the Exit For statement in the True statement block of an If...Then...Else statement. If the condition is False, the loop runs as usual.

VBScript Procedures

Kinds of procedures

In VBScript there are two kinds of procedures; the Sub procedure and the Function procedure.

Sub procedures

A Sub procedure is a series of VBScript statements, enclosed by the Sub and End Sub statements, that performs actions but does not return a value. A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses.

The following Sub procedure uses two intrinsic, or built-in, VBScript functions, InputBox and MsgBox, to prompt a user for some information. It then displays the results of a calculation based on that information. The calculation is performed in a Function procedure created using VBScript. It is shown in the discussion of the Function procedure that follows.

<SCRIPT LANGUAGE="VBScript">
<!--
 Sub ConvertTemp()
    temp = InputBox("Please enter the temperature in degrees F.", 1)
    MsgBox "The temperature is " & Celsius(temp) & " degrees C."
 End Sub
-->
</SCRIPT>

Function procedures

A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but it can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant.

In the following example, the Celsius function calculates degrees Celsius from degrees Fahrenheit. When the function is called from the ConvertTemp Sub procedure, a variable containing the argument value is passed to the function. The result of the calculation is returned to the calling procedure and displayed in a message box.

<SCRIPT LANGUAGE="VBScript">
<!--
 Sub ConvertTemp()
     temp = InputBox("Please enter the temperature in degrees F.", 1)
     MsgBox "The temperature is " & Celsius(temp) & " degrees C."
 End Sub

 Function Celsius(fDegrees)
     Celsius = (fDegrees - 32) * 5 / 9
 End Function
-->
</SCRIPT>

Declaring procedures

Because you need to define procedures before they are used, you should always put them at the beginning of the HEAD section of your HTML page. All subsequent code should also be in the HEAD section. Further, Function and Sub statements, like all other elements of the VBScript language, must be contained in paired <SCRIPT LANGUAGE="VBScript"></SCRIPT> tags to be properly recognized in HTML. In addition, comment tags (<!-- and -->) should surround the code inside the <SCRIPT> tag to ensure that it is not displayed in browsers that don't handle VBScript.

Getting data into and out of procedures

Each piece of data is passed into your procedures using an argument. Arguments serve as placeholders for the data you want to pass into your procedure. When you create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure. All arguments are placed inside these parentheses, separated by commas. For example, in the following example, fDegrees is a placeholder for the value being passed into the Celsius function for conversion:

<SCRIPT LANGUAGE="VBScript">
<!--
 Function Celsius(fDegrees)
    Celsius = (fDegrees - 32) * 5 / 9
 End Function
-->
</SCRIPT>

You can name your arguments anything that is valid as a variable name.

To get data out of a procedure, you must use a function. Remember, a Function procedure can return a value; a Sub procedure cannot.

Using Sub and Function procedures in code

To use a function in your code, it must always be used on the right side of a variable assignment or in an expression. For example:

<SCRIPT LANGUAGE="VBScript">
<!--
 Temp = Celsius(fDegrees)
-->
</SCRIPT>

or

<SCRIPT LANGUAGE="VBScript">
<!--
 MsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."
-->
</SCRIPT>

To call a Sub procedure from another procedure, you can just type the name of the procedure along with values for any required arguments, each separated by a comma. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses.

The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other does not. Both do exactly the same thing.

<SCRIPT LANGUAGE="VBScript">
<!--
 Call MyProc(firstarg, secondarg)
 MyProc firstarg, secondarg
-->
</SCRIPT>

Notice that the parentheses are omitted in the call when the Call statement isn't used.

Note   The current release supports only passing arguments by value (passing copies of the arguments). If you need to set values inside a Sub procedure, you must assign those values to variables defined outside of the procedure.

Using VBScript in Internet Explorer 3.0

A Simple VBScript Page

With Microsoft Internet Explorer 3.0, you can view the page produced by the HTML code below. If you clicked the button on the page, you'd see Microsoft Visual Basic Scripting Edition in action.

<HTML>
<HEAD><TITLE>A Simple First Page</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Button1_OnClick
        MsgBox "Mirabile visu."
End Sub
-->
</SCRIPT>
</HEAD>
<BODY>
<H3>A Simple First Page</H3><HR>
<FORM><INPUT NAME="Button1" TYPE="BUTTON" VALUE="Click Here"></FORM>
</BODY>
</HTML>

The result is a little underwhelming: you see a dialog box with a phrase in it (Latin for "wonderful to behold"). However, there's quite a bit going on.

When Internet Explorer reads the page, it finds the <SCRIPT> tags, recognizes there is a piece of VBScript code and saves the code. Then when you click the button, Internet Explorer makes the connection between the button and the code, and runs the procedure.

The Sub procedure in the <SCRIPT> tags is known as an event procedure. You'll notice that there are two parts to the procedure name: the name of the button, Button1 (from the NAME attribute in the <INPUT> tag), and an event name, OnClick; the two are joined together by an underscore. Anytime the button is clicked, Internet Explorer looks for and runs the corresponding event procedure, Button1_OnClick.

Internet Explorer 3.0 defines the events available for form controls in "Scripting Object Model" in the ActiveX SDK, on the MSDN Library.

Pages can use combinations of controls and procedures, too. A following section, VBScript and Forms, shows some simple interactions among controls.

Other Ways to Attach Code to Events

You can attach VBScript code to events in two other ways, though the way you've already seen is probably the most general and simple.

Internet Explorer 3.0 allows you to add short sections of inline code in the tag defining the control. For example, the following <INPUT> tag does precisely the same action as the previous code example when you click the button:

<INPUT NAME="Button1" TYPE="BUTTON"
       VALUE="Click Here" OnClick='MsgBox "Mirabile visu."'>

Notice that the function call itself is in single quotes and the string for the MsgBox function is in double quotes. You can use multiple statements as long as you separate the statements with colons (:).

You can also write a <SCRIPT> tag so that it applies only to a particular event for a specific control:

<SCRIPT LANGUAGE="VBScript" EVENT="OnClick" FOR="Button1">
<!--
    MsgBox "Mirabile visu."
-->
</SCRIPT>

Here, since the <SCRIPT> tag already specifies the event and the control, you don't use the Sub and End Sub statements.

VBScript and Forms

Simple validation

You can use Visual Basic Scripting Edition to do much of the form processing that you'd normally need to do on a server. You can also do things that just can't be done on the server.

Here's an example of simple client-side validation. The HTML code is for a text box and a button. If you use Microsoft Internet Explorer 3.0 to view the page produced by the code, you'd see a small text box with a button next to it.

<HTML>
<HEAD><TITLE>Simple Validation</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Submit_OnClick
  Dim TheForm
  Set TheForm = Document.ValidForm
  If IsNumeric(TheForm.Text1.Value) Then
    If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then
      MsgBox "Please enter a number between 1 and 10."
    Else
      MsgBox "Thank you."
    End If
  Else
    MsgBox "Please enter a numeric value."
  End If
End Sub
-->
</SCRIPT>
</HEAD>
<BODY>
<H3>Simple Validation</H3><HR>
<FORM NAME="ValidForm">
Enter a value between 1 and 10:
<INPUT NAME="Text1" TYPE="TEXT" SIZE="2">
<INPUT NAME="Submit" TYPE="BUTTON" VALUE="Submit">
</FORM>
</BODY>
</HTML>

The only difference between this and the "A Simple First Page" above is that the Value property of the text box is used to check the entered value. To get the Value property, however, the code has to qualify the reference to the name of the text box.

You can always write out the full reference, Document.ValidForm.Text1. However, where you have multiple references to form controls you'll want to do what was done here. First, declare a variable. Then use the Set statement to assign the form to the variable TheForm. A regular assignment statement doesn't work here: you have to use Set to preserve the reference to an object.

Using numeric values

Notice that the example directly tests the value against a number: it uses the IsNumeric function to make sure the string in the text box is a number. Although VBScript automatically converts strings and numbers as needed, it's always a good practice to test a user-entered value for its data subtype and to use conversion functions as necessary. In addition, when doing summation with text box values, convert the values explicitly to numbers since the plus sign (+ operator) represents both addition and string concatenation. For example, if Text1 contained "1" and Text2 contained "2" you'd see the following results:

A = Text1.Value + Text2.Value      ' A is "12"
A = CDbl(Text1.Value) + Text2.Value   ' A is 3

Validating and passing data back to the server

The simple validation example uses a plain button control. If it used a Submit control, the example would never see the data to check it—everything would go immediately to the server. Avoiding the Submit control lets you check the data, but it doesn't submit it to the server. That requires an additional line of code:

<SCRIPT LANGUAGE="VBScript">
<!--
Sub Submit_OnClick
  Dim TheForm
  Set TheForm = Document.ValidForm
  If IsNumeric(TheForm.Text1.Value) Then
    If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then
      MsgBox "Please enter a number between 1 and 10."
    Else
      MsgBox "Thank you."
      TheForm.Submit   ' Data correct; send to server.
    End If
  Else
    MsgBox "Please enter a numeric value."
  End If
End Sub
-->
</SCRIPT>

To send the data to the server, the code invokes the Submit method on the form object when the data is correct. From there, the server handles the data just as it otherwise would—except that the data is correct before it gets there. You'll find complete information about the Submit method and other methods in "Scripting Object Model" in the ActiveX SDK, on the MSDN Library.

So far, you've seen only the standard HTML <FORM> objects. Internet Explorer 3.0 also lets you exploit the full power of ActiveX controls and Java objects.

Going Beyond Forms—Using Objects

Using objects

Whether you use an ActiveX control or a Java object, Microsoft Visual Basic Scripting Edition and Microsoft Internet Explorer 3.0 handle it the same way.

You include an object using the <OBJECT> tags and set its initial property values using <PARAM> tags. If you're a Visual Basic programmer, you'll recognize that using the <PARAM> tags is just like setting initial properties for a control on a form. For example, the following set of <OBJECT> and <PARAM> tags adds the ActiveX Label control to a page:

<OBJECT
   classid="clsid:99B42120-6EC7-11CF-A6C7-00AA00A47DD2"
   id=lblActiveLbl
   width=250
   height=250
   align=left
   hspace=20
   vspace=0
>
<PARAM NAME="Angle" VALUE="90">
<PARAM NAME="Alignment" VALUE="4">
<PARAM NAME="BackStyle" VALUE="0">
<PARAM NAME="Caption" VALUE="A Simple Desultory Label">
<PARAM NAME="FontName" VALUE="Arial">
<PARAM NAME="FontSize" VALUE="20">
<PARAM NAME="FontBold" VALUE="1">
<PARAM NAME="FrColor" VALUE="0">
</OBJECT>

You can get properties, set properties, and invoke methods just as with any of the form controls. The following code, for example, includes <FORM> controls that you can use to manipulate two of the label control's properties:

<FORM NAME="LabelControls">
<INPUT TYPE="TEXT" NAME="txtNewText" SIZE=25>
<INPUT TYPE="BUTTON" NAME="cmdChangeIt" VALUE="Change Text">
<INPUT TYPE="BUTTON" NAME="cmdRotate" VALUE="Rotate Label">
</FORM>

With the form defined, an event procedure for the cmdChangeIt button changes the label text:

<SCRIPT LANGUAGE="VBScript">
<!--
Sub cmdChangeIt_onClick
   Dim TheForm
   Set TheForm = Document.LabelControls
   lblActiveLbl.Caption = TheForm.txtNewText.Value
End Sub
-->
</SCRIPT>

The code qualifies references to controls and values inside the forms just as in the simple validation example.

Several ActiveX controls are available from http://www.download.com/PC/Activex/. You can find information there, or on the control reference pages at http://microsoft.com/intdev/controls/ctrlref-f.htm, about the properties, methods, and events, as well as the class identifiers (CLSID) for the controls. You can find more information about the <OBJECT> tag on the Microsoft ActiveX Author's Guide and HTML Reference page at http://microsoft.com/workshop/author/newhtml/default.htm.

Note   Previous releases of Internet Explorer 3.0 required braces ({}) around the classid attribute and did not conform to the World Wide Web Consortium specification. Using braces with the current release generates a "This page uses an outdated version of the <OBJECT> tag" message.

Where to Go from Here

The fastest way to learn advanced VBScript techniques is to look at samples, lots and lots of samples. It doesn't hurt, either, to know the object model well.

Here are some places to start:

From the VBScript Web site (http://www.microsoft.com/vbscript/) check out the Samples page for a list of downloadable VBScript samples and the Related Links page for a list of sites using VBScript.

VBScript Coding Conventions

What are coding conventions?

Coding conventions are suggestions that may help you write code using Microsoft Visual Basic Scripting Edition. Some of the things that coding conventions include are:

The main reason for using a consistent set of coding conventions is to standardize the structure and coding style of a script or set of scripts so that you and others can easily read and understand the code.

Using good coding conventions results in precise, readable, and unambiguous source code that is consistent with other language conventions and as intuitive as possible.

Constant naming conventions

Constant names should be uppercase with underscores (_) between words. For example:

 USER_LIST_MAX
 NEW_LINE

Variable naming conventions

For purposes of readability and consistency, use the prefixes listed in the Table 3, along with descriptive names for variables in your VBScript.

Table 3. Conventional Prefixes for Variables in VBScript

Subtype Prefix Example
Boolean bln blnFound
Byte byt bytRasterData
Date (Time) dtm dtmStart
Double dbl dblTolerance
Error err errOrderNum
Integer int intQuantity
Long lng lngDistance
Object obj objCurrent
Single sng sngAverage
String str strFirstName

Variable scope

Variables should always be defined with the smallest scope possible. Table 4 gives the scope for VBScript variables.

Table 4. Variable Scope

Scope Where variable Is declared Visibility
Procedure-level Event, Function, or Sub procedure Visible in the procedure in which it is declared.
Script-level HEAD section of an HTML page, outside any procedure Visible in every procedure in the script.

Variable scope prefixes

As script size grows, so does the value of being able to quickly differentiate the scope of variables. A one-letter scope prefix preceding the type prefix provides this, without unduly increasing the size of variable names. See Table 5.

Table 5. Variable Scope Prefixes

Scope Prefix Example
Procedure-level None dblVelocity
Script-level s sblnCalcInProgress

Descriptive variable and procedure names

The body of a variable or procedure name should use mixed case and should be as complete as necessary to describe its purpose. In addition, procedure names should begin with a verb, such as InitNameArray or CloseDialog.

For frequently used terms or long terms, standard abbreviations are recommended to help keep name length reasonable. In general, variable names greater than 32 characters can be difficult to read.

When using abbreviations, make sure they are consistent throughout the entire script. Randomly switching between Cnt and Count within a script ,or set of scripts, may lead to confusion.

Object naming conventions

Table 6 lists recommended conventions for the various objects you may encounter while programming VBScript.

Table 6. Object Naming Conventions

Object type Prefix Example
3D Panel pnl pnlGroup
Animated button ani aniMailBox
Check box chk chkReadOnly
Combo box, drop-down list box cbo cboEnglish
Command button cmd cmdExit
Common dialog dlg dlgFileOpen
Frame fra fraLanguage
Horizontal scroll bar hsb hsbVolume
Image img imgIcon
Label lbll blHelpMessage
Line lin linVertical
List box lst stPolicyCodes
Spin spn spnPages
Text box txt txtLastName
Vertical scroll bar vsb vsb
RateSlider sld sldScale

Code commenting conventions

All procedures should begin with a brief comment describing what they do. This description should not describe the implementation details (how it does it) because these often change over time and may result in unnecessary comment maintenance work, or worse, erroneous comments. The code itself and any necessary inline comments describe the implementation.

Arguments passed to a procedure should be described when their purpose is not obvious and when the procedure expects the arguments to be in a specific range. Function return values and other variables that are changed by the procedure, especially through reference arguments, should also be described at the beginning of each procedure.

Procedure header comments should include the section headings listed in Table 7. For examples, see the section "Formatting Your Code" that follows.

Table 7. Section Headings and Comment Contents

Section heading Comment contents
Purpose What the procedure does (not how).
Assumptions List of any external variable, control, or other element whose state affects this procedure.
Effects List of the procedure's effect on each external variable, control, or other element.
Inputs Explanation of each argument that is not obvious. Each argument should be on a separate line with inline comments.
Return Values Explanation of the value returned.

Remember the following points:

Formatting your code

Screen space should be conserved as much as possible while still allowing code formatting to reflect logic structure and nesting. Here are a few pointers:

Formatting your pages

Examples on the Visual Basic Scripting Web site use the following template:

<!DOCTYPE HTML PUBLIC "-//IETF/DTD HTML//EN">
<!-- Recommended template for
     Microsoft Visual Basic Scripting-Enabled Pages -->
<HTML>
<HEAD>
<TITLE> </TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
   Function CanDeliver (Dt)
      CanDeliver = (Cdate(Dt) - Now()) > 2
   End Function
-->
</SCRIPT>
</HEAD>
<BODY>
<FONT FACE=ARIAL SIZE=2> <!-- global default -->
<!-- Static page content goes here. -->
</FONT>
</BODY>
</HTML>

The template has the following features:

In addition, many sites use <FORM> tags around groups of <INPUT> elements to make controls viewable in all browsers.

Appendix: Conversion Functions

Asc Function

Returns the American National Standards Institute (ANSI) character code corresponding to the first letter in a string.

Syntax

Asc(string)

The string argument is any valid string expression. If the string contains no characters, a run-time error occurs.

Note   Another function (AscB) is provided for use with byte data contained in a string. Instead of returning the character code for the first character, AscB returns the first byte. AscW is provided for 32-bit platforms that use Unicode characters. It returns the Unicode (wide) character code, thereby avoiding the conversion from Unicode to ANSI.

CBool Function

Returns an expression that has been converted to a Variant of subtype Boolean.

Syntax

CBool(expression)

The expression argument is any valid expression.

Remarks

If expression is zero, False is returned; otherwise, True is returned. If expression can't be interpreted as a numeric value, a run-time error occurs.

CByte Function

Returns an expression that has been converted to a Variant of subtype Byte.

Syntax

CByte(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CByte to force byte arithmetic in cases where currency, single-precision, double-precision, or integer arithmetic normally would occur.

You should use the CByte function instead of Val to provide internationally aware conversions from any other data type to a Byte subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Byte subtype, an error occurs.

CDate Function

Returns an expression that has been converted to a Variant of subtype Date.

Syntax

CDate(date)

The date argument is any valid date expression.

Remarks

Use the IsDate function to determine if date can be converted to a date or time. CDate recognizes date and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number to a date, the whole number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight.

CDate recognizes date formats according to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In addition, a long date format is not recognized if it also contains the day-of-the-week string.

CDbl Function

Returns an expression that has been converted to a Variant of subtype Double.

Syntax

CDbl(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or CSng to force double- or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.

You should use the CDbl function instead of Val to provide internationally aware conversions from any other data type to a Double subtype. For example, different decimal separators and thousands separators are properly recognized depending on the locale setting of your system.

Chr Function

Returns the character associated with the specified ANSI character code.

Syntax

Chr(charcode)

The charcode argument is a number that identifies a character.

Remarks

Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character.

Note   Another function (ChrB) is provided for use with byte data contained in a string. Instead of returning a character, which may be one or two bytes, ChrB always returns a single byte. ChrW is provided for 32-bit platforms that use Unicode characters. Its argument is a Unicode (wide) character code, thereby avoiding the conversion from ANSI to Unicode.

CInt Function

Returns an expression that has been converted to a Variant of subtype Integer.

Syntax

CInt(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.

You should use the CInt function instead of Val to provide internationally aware conversions from any other data type to an Integer subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Integer subtype, an error occurs.

Note   CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

CLng Function

Returns an expression that has been converted to a Variant of subtype Long.

Syntax

CLng(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur. You should use the CLng function instead of Val to provide internationally aware conversions from any other data type to a Long subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Long subtype, an error occurs.

Note   CLng differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CLng function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

CSng Function

Returns an expression that has been converted to a Variant of subtype Single.

Syntax

CSng(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or CSng to force double- or single-precision arithmetic in cases where currency or integer arithmetic normally would occur. You should use the CSng function instead of Val to provide internationally aware conversions from any other data type to a Single subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Single subtype, an error occurs.

CStr Function

Returns an expression that has been converted to a Variant of subtype String.

Syntax

CStr(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CStr to force the result to be expressed as a String. You should use the CStr function instead of Str to provide internationally aware conversions from any other data type to a String subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system.

The data in expression determines what is returned according to Table 8.

Table 8. Expression Types

If expression is CStr returns
Boolean A String containing True or False.
Date A String containing a date in the short-date format of your system.
Null A run-time error.
Empty A zero-length String ("").
Error A String containing the word Error followed by the error number.
Other numeric A String containing the number.

Hex Function

Returns a string representing the hexadecimal value of a number.

Syntax

Hex(number)

The number argument is any valid expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

Table 9. Number Argument and Hex Returns

If number is Hex returns
Null Null
Empty Zero (0).
Any other number Up to eight hexadecimal characters.

You can represent hexadecimal numbers directly by preceding numbers in the proper range with &H. For example, &H10 represents decimal 16 in hexadecimal notation.

Oct Function

Returns a string representing the octal value of a number.

Syntax

Oct(number)

The number argument is any valid expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

Table 10. Number Argument and Oct Returns

If number is Oct returns
Null Null
Empty Zero (0).
Any other number Up to 11 octal characters.

You can represent octal numbers directly by preceding numbers in the proper range with &O. For example, &O10 is the octal notation for decimal 8.