Chapter 21

Unleashing the Power of VBScript


CONTENTS


VBScript is Microsoft's scripting language for the Internet. Similar in functionality to JavaScript, VBScript has been designed to leverage the skills of millions of Visual Basic programmers to the Internet. Although JavaScript is a powerful scripting language, it is not as easy to learn and use as VBScript. VBScript can be used to easily create active Web pages. Since VBScript is supported by Microsoft, in the near future you will also see a great deal of VBScript/Windows NT/95/MSOfficeBackoffice integration, unlike JavaScript. VBScript code is lightweight, fast, and has been optimized to be transmitted via the Internet. You should spend some time with VBScript and learn how it can be used to enhance a Web site by making it easier and more exciting to navigate. By the time you read this, you can expect to see VBScript supported by several other Web browsers in addition to Internet Explorer-specifically, browsers from Oracle, Spyglass, and NetManage.

Introduction to VBScript

VBScript is a subset of Microsoft Visual Basic and is upwardly compatible with Visual Basic for Applications (VBA). VBA is shipped with MS Office applications to make it easier for developers to build custom solutions using MS Office applications. The ability to provide scripting, automation, and customization capabilities for Web browsers is a major feature of VBScript. If you are already familiar with Visual Basic, very shortly you will be able to leverage your skills to the Internet using VBScript. Even if you are not familiar with another programming language, after reading this chapter you will be able to create active Web pages using VBScript. However, familiarity with a programming language will make it easier for you to grasp various concepts such as recursion, type casting, and Boolean arithmetic. Several VBScript applications are included in the CD-ROM; experiment with them to become more familiar with VBScript. Visit the Microsoft VBScript home page for the most up-to-date information about VBScript.

URL
Visit the Microsoft VBScript information Web site for the latest information about VBScript.
http://www.microsoft.com/VBScript

How VBScript Works

VBScript programs are defined between two HTML tags. Browsers that support VBScript read the VBScript program contained between the two HTML tags and execute it after checking for any syntax errors. VBScript works as shown in Figure 21.1.

Figure 21.1: How VBScript works.

As you can see in Figure 21.1, a VBScript program is part of a regular HTML file and is enclosed between two HTML tags, <SCRIPT LANGUAGE=VBS> and </SCRIPT>. When a Web browser that supports VBScript encounters the <SCRIPT LANGUAGE=VBS> HTML tag, all text between that tag and </SCRIPT> is treated as a VBScript program and is interpreted for syntax errors. If any syntax errors are detected, they are flagged by the VBScript interpreter as shown in Figure 21.2.

Figure 21.2: Syntax errors in VBScript programs are flagged by the VBScript interpreter.

If the code does not contain any syntax errors, it is executed on the Web browser. In order to hide VBScript code from "technologically challenged" Web browsers, VBScript code can be enclosed in two HTML comment tags as shown below.

<SCRIPT LANGUAGE=VBS>
<!-- To hide VBScript code from technologically challenged browsers
… VBScript code …
!-->
</SCRIPT>

Hello World!

Writing the classic Hello World! application with VBScript is very easy. For the purpose of this example, you will be shown how to create a Web page similar to the one in Figure 21.3. This Web page will have three buttons. The first button will display a message box with a greeting, the second button will display the current time, and the third button will display today's date.

Figure 21.3: The classic Hello World! application written with VBScript.

If you would like to experiment with the VBScript application shown in Figure 21.3, it can be found in the CD-ROM that accompanies this book in the directory \Chapter-21\Hello.htm. Various key elements of the Hello World! VBScript program are outlined next.

The Hello World! Dialog Box

As shown in Figure 21.4, the Hello World! dialog box is shown each time a user clicks on the Please click here for message box button in Figure 21.3. If you look at the HTML page the VBScript program is in, you will see that the command button associated with the Hello World! dialog box is named BtnHello (NAME="BtnHello"). As you can see from the following listing, the OnClick event is associated with the BtnHello subroutine. Each time a user clicks on the Please click here for message box button in Figure 21.3, the Web browser invokes the BtnHello_OnClick subroutine and any VBScript code defined in that subroutine is executed.

Figure 21.4: The Hello World! dialog box.

The BtnHello_OnClick subroutine is a very simple VBScript subroutine. The first three lines create strings displayed by the dialog box in Figure 21.4. Note how the string concatenation operator (&) is used in line 4 to merge two strings into one and assign the result to a variable. The result is then displayed in a message box, as shown in Figure 21.4.

Note
Line numbers in various code segments are not part of the VBScript code. The line numbers are only there for reference purposes.

1: Sub BtnHello_OnClick
2:  titleString = "Web Site Developer's Guide for Windows NT"
3:  helloString = "Hello world! Welcome to the fun filled "
4:  helloString = helloString & "world of VBScript programming!"
5:  MsgBox helloString, 0, titleString
6: End Sub

Time Dialog Box

The BtnTime_OnClick subroutine is very similar to the BtnHello_OnClick subroutine. The only difference is the fact that rather than concatenating two strings, it concatenates a string with the result of a function. The time function returns the current time. As shown in Figure 21.5, line 3 of the following program listing displays the current time in a dialog box.

Figure 21.5: Time dialog box.

1: Sub BtnTime_OnClick
2:  timeString = "So, you want to know the time? The time is " & time
3:  MsgBox  timeString , 0, "Time Dialog Box"
4: End Sub

Date Dialog Box

The date dialog box displays the current date in a dialog box, as shown in Figure 21.6. As you can see in line 2 of the following code listing, the result of one function (date) can be used as an argument of another function (DateValue).

Figure 21.6: Date dialog box.

1: Sub BtnDate_OnClick
2:  dateString = "Today's date is " & DateValue(date)
3:  MsgBox  dateString , 0, "Date Dialog Box"
4: End Sub

For your reference, the full source code of the Hello World! application is listed next.


Listing 21.1. The Hello World! Web page.

!--
(C) 1996 Sanjaya Hettihewa (http://wonderland.dial.umd.edu)
All Rights Reserved.
!-->

<HTML>
<HEAD>
<TITLE>VBScript Tutorial: Hello World!</TITLE>
</HEAD>

<BODY BGCOLOR="#FFFFFF" TEXT="#0000FF"
      LINK="#B864FF" VLINK="#670000" ALINK="#FF0000">

<IMG SRC="vbscript.jpg"><P>

<B><FONT FACE="Comic Sans MS" SIZE=6 COLOR=RED>
VBScript Tutorial: <FONT></B>
<I><FONT FACE="Comic Sans MS" SIZE=5 COLOR=BLUE>
 "Hello World!" </I><P><FONT>

<form>
<INPUT TYPE=BUTTON VALUE="Please click here for message box"
       NAME="BtnHello">
<INPUT TYPE=BUTTON VALUE="What time is it?"
       NAME="BtnTime">
<INPUT TYPE=BUTTON VALUE="What date is it?"
       NAME="BtnDate">
</form>
<SCRIPT LANGUAGE=VBS>
<!-- To hide VBScript code from technologically challenged browsers

Sub BtnHello_OnClick
 titleString = "Web Site Developer's Guide for Windows NT"
 helloString = "Hello world! Welcome to the fun filled "
 helloString = helloString & "world of VBScript programming!"
 MsgBox helloString, 0, titleString
End Sub

Sub BtnTime_OnClick
 timeString = "So, you want to know the time? The time is " & time
 MsgBox  timeString , 0, "Time Dialog Box"
End Sub

Sub BtnDate_OnClick
 dateString = "Today's date is " & DateValue(date)
 MsgBox  dateString , 0, "Date Dialog Box"
End Sub
!-->
</SCRIPT>

</BODY>

</HTML>

VBScript Operators

VBScript supports several operators for various string, Boolean, and number-manipulation tasks. Various operators supported by VBScript are listed next.

Addition Operator

Syntax: <operand1> + <operand2>

The addition operator can be used to add two operands together. If both operands are numeric, the result of the addition operator will also be numeric. However, if they are strings, VBScript will instead do a string concatenation instead of a numeric addition. To avoid ambiguity, it is recommended that you use the string concatenation operator (&) when joining strings, and use the addition operator (+) when adding numeric expressions.

Subtraction Operator

Syntax: <operand1> - <operand2>
Syntax: -<OperandToNegate>

The subtraction operator is used as a unary minus and the binary subtraction operator. When used as the binary subtraction operator, it subtracts <operand2> from <operand1> and returns the resulting value. When used as the unary minus, it negates the numeric operand it is used with.

Multiplication Operator

Syntax: <operand1> ^ <operand2>

The multiplication operator takes two numeric operands, multiplies them, and returns the resulting value.

Exponential Operator

Syntax: <operand1> ^ <operand2>

Returns the resulting value of <operand1> raised to the <operand2> power.

Floating-Point Division Operator

Syntax: <operand1> / <operand2>

The division operator is used to divide <operand1> from <operand2>. Both <operand1> and <operand2> have to be numeric expressions, and the resulting value is a floating-point number.

Integer-Division Operator

Syntax: <operand1> \ <operand2>

The integer-division operator is somewhat similar to the floating-point division operator. The integer-division operator returns an integer number after dividing <operand1> from <operand2>. If you wish to experiment with this operator, refer to \Chapter-21\Int.htm in the CD-ROM. A few examples of the integer division operator are listed next.

( 23 \ 4 ) = 5
( 4 \ 23 ) = 0
( 4 \ 2 ) = 2
( 5 \ 2 ) = 2

String-Concatenation Operator

Syntax: <operand1> & <operand2>

The string-concatenation operator can be used to join <operand1> and <operand2> together.

MOD Operator

Syntax: <operand1> MOD <operand2>

The MOD operator is somewhat similar to the integer-division operator. The only difference is the fact that it returns the remainder of <operand1> divided by <operand2>. If you wish to experiment with this operator, refer to \Chapter-21\Mod.htm in the CD-ROM. A few examples of the MOD operator are listed next.

( 23 MOD 4 ) = 3
( 4 MOD 23 ) = 4
( 4 MOD 2 ) = 0
( 5 MOD 2 ) = 1

Boolean Operators

VBScript supports a number of Boolean operators. The best way to explain how Boolean operators work is with a truth table. Refer to Figure 21.7 for truth tables of a number of useful VBScript Boolean operators. Various useful VBScript Boolean operators are listed next, along with how they can be used in VBScript programs.

Figure 21.7: Truth tables of VBScript Boolean operators.

AND Operator

Syntax: <operand1> AND <operand2>

The AND operator returns TRUE if both <operand1> and <operand2> are true. If not, it returns FALSE. The AND operator can be used with expressions and functions that return a Boolean value.

OR Operator

Syntax: <operand1> OR <operand2>

The OR operator returns TRUE if either <operand1> or <operand2> is true. The OR operator can be used with expressions and functions that return a Boolean value.

NOT Operator

Syntax: NOT <operand>

The NOT operator can be used to negate a Boolean value. The NOT operator can be used with expressions and functions that return a Boolean value.

XOR Operator

Syntax: <operand1> XOR <operand2>

The XOR operator is very similar to the OR operator. The only difference is the fact that in order for the XOR operator to return TRUE, <operand1> or <operand2> has to be true. However, they both can't be true at the same time. The NOT operator can be used with expressions and functions that return a Boolean value.

Equivalence Operator

Syntax: <operand1> Eqv <operand2>

The equivalence operator can be used to determine if <operand1> is equal to <operand2>. If either <operand1> or <operand2> is NULL, then the resulting value will also be NULL. The truth table of the equivalence operator is listed next.

TRUE Eqv TRUE = TRUE
FALSE Eqv TRUE = FALSE
TRUE Eqv FALSE = FALSE
FALSE Eqv FALSE = TRUE

(TRUE may be replaced with binary 1 and FALSE may be replaced with binary 0.)

Object-Reference Operator

Syntax: <operand1> IS <operand2>

The object-reference operator is used to compare two object reference variables. If <operand1> refers to the same object as <operand2>, the object-reference operator returns TRUE. Otherwise, it returns FALSE.

Comparison Operators

VBScript supports several comparison operators. These comparison operators can be used to compare strings as well as numbers. Various comparison operators that can be used in VBScript programs are listed next.

Equal Operator

Syntax: <operand1> = <operand2>

Returns TRUE if both <operand1> and <operand2> are equal to each other. However, if either <operand1> or <operand2> is NULL, the equal operator will return NULL.

Unequal Operator

Syntax: <operand1> <> <operand2>

Returns TRUE if both <operand1> and <operand2> are unequal to each other. However, if either <operand1> or <operand2> is NULL, the unequal operator will return NULL.

Less Than Operator

Syntax: <operand1> < <operand2>

Returns TRUE if <operand1> is less than <operand2>. However, if either <operand1> or <operand2> is NULL, the less than operator will return NULL.

Less Than or Equal to Operator

Syntax: <operand1> <= <operand2>

Returns TRUE if <operand1> is less than or equal to <operand2>. However, if either <operand1> or <operand2> is NULL, the less than or equal to operator will return NULL.

Greater Than Operator

Syntax: <operand1> > <operand2>

Returns TRUE if <operand1> is greater than <operand2>. However, if either <operand1> or <operand2> is NULL, the greater than operator will return NULL.

Greater Than or Equal to Operator

Syntax: <operand1> >= <operand2>

Returns TRUE if <operand1> is greater than or equal to <operand2>. However, if either <operand1> or <operand2> is NULL, the greater than or equal to operator will return NULL.

VBScript Control Structures

Control structures are an important part of any language. They give a language "life" by allowing programmers to add intelligence to programs with conditional and iterative statements. Various VBScript control structures are listed next, along with how they can be used in VBScript programs.

Call

Call is used to transfer program control to another VBScript subroutine. Note that when Call is used to transfer control to another subroutine, if that subroutine has any parameters, they should be enclosed in parentheses. However, if Call is omitted, subroutine arguments do not need to be enclosed in parentheses. Return values of functions are ignored when they are invoked with the Call statement.

Dim

The Dim statement is used to declare variables, such as arrays, and assign them storage space. When variables are declared with Dim, if they are numeric variables, they are initialized with the value zero. Otherwise, they are assigned an empty string. The Dim statement can be used to declare several types of variables. Various types of variables that can be created with the Dim statement are listed next.

Declaring Variant Variables

Syntax: Dim <VariableName1> , <VariableName2>

This statement can be used to declare variables of variant type. As shown here, several variables can be defined at the same time by separating them with commas.

Multiple Variables Declarations

Syntax: Dim <VariableName1> As Integer, <VariableName2>

One Dim statement can be used to declare several variables of more than one type. As in the case of the previous Dim command, <VariableName1> is declared as an integer variable and <VariableName2> is declared as a variant variable.

Declaring Static Arrays

Single Dimension Array Syntax: Dim <NameOfArray>(50)

The Dim statement can be used to define arrays. In this example, an array of 50 storage locations of type variant is created using the Dim statement. If an index range is not specified for an array, VBScript will index the array starting at zero. For example, in this case, <NameOfArray> is indexed from 0 to 49.

Multi Dimension Array Syntax: Dim <NameOfArray>(5,1 To 5)

The Dim statement can also be used to declare multidimensional arrays. For example, the preceding statement can be used to declare a two-dimensional array by the name of <NameOfArray>. As shown in this example, the index range of an array can be customized by using a number range (1 To 5). By adding an As <VariableType> command to an array declaration, it is possible to define an array of a certain data type.

Declaring Dynamic Arrays

If you are unsure about the size of an array when it is first declared, VBScript allows the creation of dynamic arrays. Dynamic arrays can be expanded or reduced as needed. Dynamic arrays can be created using the following syntax.

Dim <NameOfArray>()

Storage space for additional elements can be allocated for a dynamic array using the ReDim statement, as shown next. (Simply indicate, in parentheses, the number of elements the array should have.)

ReDim <NameOfArray>(10)

As an added incentive, VBScript dynamic arrays can be expanded while preserving existing array values. As shown in the next example, this is done by adding a Preserve statement in between the ReDim statement and the array name.

ReDim Preserve <NameOfArray>(20)

Note that if a data type was defined for a dynamic array using the As statement, the array's data type cannot be changed using the ReDim statement. Also, if a dynamic array is reduced in size, using the ReDim statement, any data stored in the portion of the array that was deleted is permanently lost.

Do/While/Until/Loop

The Do/Loop control structure can be used to iterate a group of statements until a certain Boolean expression becomes TRUE. The syntax of the Do/Loop control structure is listed next. As shown in the following example, the Boolean expression of a Do/Loop structure can be placed either at the beginning or the end.

Do <condition> <BooleanExpression>
… VBScript statements …
Loop

As shown next, the Boolean expression of a Do/Loop structure can also be placed at the end of the control structure.

Do
… vbscript statements …
Loop <condition> <booleanexpression>

The preceding two examples will repeatedly execute VBScript statements enclosed in the loop structure until <BooleanExpression> becomes TRUE. In the examples, <condition> may be replaced with either While or Until. As the name implies, if While is used, the loop will iterate while <BooleanExpression> is TRUE. In the like manner, if Until is used, the loop will iterate until <BooleanExpression> is TRUE. Note that within a Do/Loop structure, it is possible to transfer control out of the loop using an Exit Do statement.

Erase

Syntax: Erase <NameOfArray>

The Erase statement is used to free memory used by dynamic arrays and reinitialize elements of static arrays. If the array is a dynamic array, all space taken up by the array is freed. Dynamic arrays then need to be reallocated using the ReDim statement before they can be used again. If the array is a static array, all array elements are initialized with zero if its elements are numeric or empty strings otherwise.

Exit

The Exit statement causes program control to be transferred out of the control structure it is used in. The control structure can be a loop or a subroutine. Various forms of the Exit command are listed next.

Exit Do-Exits a Do loop.
Exit For-Exits a For loop.
Exit Function-Exits a function.
Exit Sub-Exits a procedure.

For/Next

The For/Next control structure can be used to iterate a group of VBScript statements a certain number of times. The syntax of the For/Next control structure is listed next.

For <LoopCount> = <BeginLoop> To <EndLoop> Step <StepCount>
… VBScript statements …
Next

The previous definition can be used to iterate a group of VBScript statements a certain number of times by replacing various labels (enclosed in pointed braces) of the definition, as follows:

<LoopCount>-Name of variable used to keep track of the number of iterations. It's best that your VBScript statements do not alter the value of this variable, because it can easily complicate your code and make it harder to debug.
<BeginLoop>-The first value of the iteration sequence.
<EndLoop>-The last value of the iteration sequence.
Step <StepCount>-<StepCount> can be replaced with the <LoopCount>, which will be incremented after each iteration of the loop. The Step statement is optional; by default, <LoopCount> will be incremented by one.

Note that the Exit For statement can be used to exit a For loop.

For Each/Next

The For Each/Next control structure is useful for iterating VBScript statements for each object in a collection or each element in an array. The syntax of the For Each/Next loop is listed next.

For Each <LoopIndex> In <ArrayOrCollection>
… VBScript statements …
Next <LoopIndex>

A For Each/Next loop can be added to a VBScript program by substituting various labels of the preceding example, as follows.

<LoopIndex>-Name of variable that's used to traverse through the elements of an array or objects in a collection.
<ArrayOrCollection>-Name of an array or collection of objects.

Note that the Exit For statement can be used to exit a For Each loop. Also note that <LoopIndex> can be omitted in the Next <LoopIndex> statement. However, this is not recommended; it can complicate things and cause errors if a For Each loop is nested inside another For Each loop.

Function

New functions can be defined using the Function statement. The syntax of the Function statement is as follows:

<FunctionType> Function <NameOfFunction> <ArgumentsOfFunction>
… VBScript statements …
<NameOfFunction> = <ReturnValueOfFunction>
End Function

A function can be created by replacing various labels of the above definition with the values listed next.

<FunctionType>-The <FunctionType> can be left out if it is not needed. By replacing <FunctionType> with Static, it is possible to preserve values of local variables in between function calls. Unless you have a reason for doing so, Static functions are usually not suitable for recursion (a function calling itself).
<NameOfFunction>-Used to specify the name of the function.
<ArgumentsOfFunction>-Arguments of a function can be specified soon after <NameOfFunction>. By using commas, more than one argument can be specified. An argument can be passed either by value or reference. In order to make an argument pass by value, precede the argument name with ByVal; to pass by reference, precede the argument name with ByRef. When an argument is passed by value, its original value cannot be changed from within the function. However, when it is passed by reference, the variable used in the function is merely a pointer to the original variable. Therefore, any changes made to the value of a variable passed by reference are actually made to the original variable.

Note that the Exit Function statement can be used to exit a function. VBScript procedures created with the Function statement are very similar to procedures created with the SUB statement. The only difference is that procedures created with the Function statement can return values, whereas procedures created with the Sub statement cannot.

If/Then/Else

The If/Then/Else statement can be used to execute various VBScript statements based on Boolean expressions. The syntax of the If/Then/Else control structure is as follows:

IF <BooleanExpression> THEN
… VBScript statement …
ELSE IF <BooleanExpression> THEN
… VBScript statement …
ELSE
… VBScript statement …
END IF

As shown in the previous example, various VBScript statements can be made to execute using an If/Then/Else statement based on various Boolean expressions.

Let

The Let command can be used to assign values to variables. The Let command is not required to assign a value to a variable. The syntax of the Let command is as follows:

Let <variableName> = <ValueOfVariable>

LSet

LSet is used to copy a variable of one user-defined type to a variable of another user-defined type. When a variable is copied with the LSet command, it is left-aligned. The syntax of the LSet statement is listed next.

LSet <Variable> = <ValueOfVariable>

If the length of <Variable> is longer than that of <ValueOfVariable>, after copying <ValueOfVariable> to <Variable> the remaining space will be filled in with white spaces. In the like manner, if the length of <Variable> is less than that of <ValueOfVariable>, <ValueOfVariable> will be truncated to fit in the space allocated for <Variable>. For example, if <Variable> can hold only four characters, and <ValueOfVariable> contains the string "ABCDEFG", after it is copied to <Variable> with the LSet command, <Variable> will have the value "ABCD."

Mid

Mid is a very handy statement for replacing one or more characters of a string with characters from another string. The syntax of the Mid statement is listed next.

Mid (<Variable>, <Begin>, <NumCharactersToReplace>) = <Replacement>

The Mid statement can be used by replacing various labels of the preceding example, as follows:

<Variable>-Name of variable containing the string that will be modified.
<Begin>-The position to begin replacing text. For example, if <Variable> contained the string "1234" and you would like "34" to be replaced with "67", <Begin> will be replaced with "3" because the sub string "34" begins at the third position.
<NumCharactersToReplace>-Lists the number of characters that should be replaced by <Replacement>. This value can be left out if you wish, in which case the entire <Replacement> string will be copied over.
<Replacement>-Contains string that will be copied over to <Variable>.

On Error

Usually, when a runtime error occurs in a VBScript program, it halts execution of the VBScript program. Using the On Error Resume Next statement, however, it is possible to ignore the error and continue with the program.

Private

By preceding a variable declaration with the Private keyword, it is possible to limit its scope to the script it was declared in.

Public

By preceding a variable declaration with the Public keyword, the scope of a variable can be extended to other scripts.

Randomize

Can be used to initialize the random-number generator. Randomize can be used either with or without a numeric argument. If it is used with a numeric argument, the numeric argument is used to seed the random-number generator. If Randomize is used without an argument, a number from the system clock is used to seed the random-number generator.

Rem

The Rem command is used to document VBScript code. The syntax of the Rem command is listed next.

Rem This is a comment

Note that the apostrophe (') is equivalent in functionality to the Rem command. The only difference between the Rem statement and the apostrophe is the fact that if Rem is used in the same line with a VBScript statement, it needs to be separated from the VBScript statement with a colon.

RSet

The syntax of the RSet command is listed next.

RSet <Variable> = <StringToCopy>

The RSet command is similar in functionality to the LSet command. The only difference is the fact that when a variable is assigned a string using the RSet command, it is assigned to the variable right-aligned.

Set

The Set command can be used to assign an object reference to a variable or property. The syntax of the Set command is as follows.

Set <ObjectVariable> = <Object>

When the keyword Nothing is assigned to <ObjectVariable>, system resources consumed by the object are freed when no other variables refer to the <Object>.

Static

By preceding variable and procedure declarations with the keyword Static, it is possible to retain values of variables. When a procedure is declared as a static procedure, all variables in that procedure retain values assigned to them throughout the life of the program. Precede variable declarations of nonstatic procedures with the Static keyword to preserve their values. (Variable values of static procedures are automatically preserved.)

Sub

The Sub statement can be used to create VBScript procedures and is identical to the Function statement except for one difference. Procedures created with the Function statement can return values; procedures created with the Sub statement cannot. The syntax of the Sub statement is listed next. Note that the Exit Sub statement can be used to transfer control out of a procedure. The syntax of the Sub statement is listed next.

<ProcedureType> Sub <NameOfProcedure> <ArgumentsOfProcedure>
… VBScript statements …
End Sub

A procedure can be created by replacing various labels of the preceding definition with the values listed next:

<ProcedureType>-The <ProcedureType> can be left out if it is not needed. By replacing <ProcedureType> with Static, it is possible to preserve values of local variables in between procedure calls. Unless you have a reason for doing so, Static functions are usually not suitable for recursion (a function calling itself).
<NameOfProcedure>-Used to specify the name of the procedure.
<ArgumentsOfProcedure>-Arguments of a procedure can be specified soon after <NameOfProcedure>. By using commas, more than one argument can be specified. An argument can be passed either by value or reference. In order to make an argument pass by value, precede the argument name with ByVal, and to pass by reference, precede the argument name with ByRef. When an argument is passed by value, its original value cannot be changed from within the procedure. However, when it is passed by reference, the variable used in the procedure is merely a pointer to the original variable. Therefore, any changes made to the value of a variable passed by reference is actually made to the original variable.

While/Wend

The While/Wend control structure can be used to iterate a group of VBScript statements while a certain Boolean expression is true. The syntax of the While/Wend command is listed next.

While <BooleanExpression>
… VBScript statements …
Wend

VBScript Functions

Various functions supported by VBScript are listed next. The following functions can be used to add a new level of interactivity to a Web site by creating active Web pages. Shortly, you will be shown how these functions can be used to develop various VBScript programs.

Abs

The Abs function can be used to obtain the absolute value of a number. For example, Abs(-30) = 30 = Abs(30).

Array

The Array function can be used to quickly create an array because it returns a variant containing an array. An example of how the Array function can be used is given next. The following two commands create an array with three elements. After the two commands are executed, Colors(2) will equal "Blue."

Dim Colors As Variant
Colors = Array ( "Red", "Blue", "Green" )

Asc

Returns the ASCII character code of a character or the first character of a string. For example, Asc ("A") returns 65 and so does Asc ("America").

Atn

Returns the arctangent of a number.

CBool

Returns the Boolean value of an expression passed into the function. For example, CBool ( A = B ) will return TRUE if both A and B contain the same value.

CByte

Converts a number passed into the function into a number of type byte and returns it. For example, if CByte is called with the number 123.678, it will return 123.

CDate

If a valid date expression is passed into the function, it is converted into date type and returned. Before passing an expression to the CDate function, it is possible to determine if it can be converted by CDate into date type by using the IsDate function.

CDbl

Converts an expression passed into the function into a variant of subtype double.

Chr

Returns the ASCII character of an ASCII code. For example, Chr(65) returns the character A.

CInt

Converts an expression into a variant of subtype Integer. For example, CInt (1234.567) returns 1235.

CLng

Returns a variant of subtype long after the expression passed into the function is converted into long. For example, CLng (12345.67) returns 12346.

Cos

Returns the cosine of an angle passed into the function.

CSng

Converts a numerical expression passed into the function into a variant of subtype Single. For example, CSng (12.123456) returns 12.12346.

CStr

Converts an expression passed into CStr into a string and returns it. For example, CStr(123.456) returns the value "123.456".

CVErr

Used to return a user-specified error code. The syntax of CVErr is CVErr(ErrorNumber).

Date

Returns the date from the system clock. The value returned by the Date command at the time of this writing is 4/1/1996.

DateSerial

DateSerial is a handy function that can be used to calculate various days. By using numerical expressions and using the DateSerial function, it is possible to count backward and forward from a date simply by adding and subtracting numbers. The syntax of the DateSerial function is as follows:

DateSerial (<Year>, <Month>, <Day>)

If the current date is 4/1/1996, for example, DateSerial(1996,4-2,1+28) returns the value 2/29/1996. (Of course, if the year was 1997 (not a leap year), the result would have been 3/1/1996.)

DateValue

Converts an expression passed into the function into a variant of subtype date and returns it. For example, DateValue("February 29, 1976") returns 2/29/1976. If the year is left out, it will be obtained from the system clock.

Day

The Day function returns a value between 1 and 31 and can be used to find the day of a date. For example, Day("4/1/1996") returns 1.

Exp

Returns the value of e raised to a power. For example Exp(1) returns 2.71828182845905.

Hex

Returns the hexadecimal (base 16) value of a numerical expression. For example, Hex(10) returns A.

Hour

Returns the number of hours of a time expression. For example, Hour("12:25:34") returns 12.

InputBox

The InputBox function is used to obtain input from the user by presenting a dialog box. The syntax of the InputBox command is as follows:

InputBox(<Prompt>,<Title>,<Default>,<X>,<Y>)

Various arguments of the above command enclosed in pointed brackets can be replaced with the following values:

InStr

Returns the location of one string in another string. The syntax of InStr is as follows:

InStr (<BeginPosition>, <String1>, <String2>, <ComparisonType>

Int, Fix

Both Int and Fix convert numerical expressions into integers. The only difference is the fact that Int converts a negative number with a fraction into a smaller integer, and Fix converts a negative number with a fraction into a larger integer. The following examples illustrate how Int and Fix handle numbers with fractions.

Int(11.75) = 11
Fix(11.75) = 11
Int(12.45) = 12
Fix(12.45) = 12
Int(-17.75) = -18
Fix(-17.75) = -17
Int(-7.25) = -8
Fix(-7.25) = -7

IsArray

Returns TRUE if a variable is an array and FALSE otherwise.

IsDate

Returns TRUE if an expression can be converted to a valid date and FALSE otherwise.

IsEmpty

Returns TRUE if a variable has been initialized and FALSE otherwise.

IsError

Returns TRUE if an expression is an error code and FALSE otherwise.

IsNull

Returns TRUE if an expression is NULL and FALSE otherwise.

IsNumeric

Returns TRUE if an expression is numeric and FALSE otherwise.

IsObject

Returns TRUE if an expression references an OLE Automation Object and FALSE otherwise.

LBound

LBound can be used to find the minimum index of an array dimension. For example, if ArrayVariable is a three-dimensional array declared with the statement Dim ArrayVariable(5 To 100, 10 To 200, 20 To 300), UBound(ArrayVariable,1) returns 5, LBound(ArrayVariable,2) returns 10, and of course LBound(ArrayVariable,3) returns 20.

LCase

Converts a string expression to lowercase and returns it.

Left

Returns a certain number of characters from the left side of a string. For example, Left("Windows NT", 7) returns "Windows."

Len

Returns the number of characters of a string expression.

Log

Returns the natural logarithm of a nonnegative, numerical expression.

LTrim, RTrim, Trim

Eliminates spaces from a string and returns it. LTrim eliminates preceding spaces, RTrim eliminates trailing spaces, and Trim eliminates both trailing and preceding spaces.

Mid

Returns a certain number of characters from a string. For example Mid("Windows NT", 0, 7) returns "Windows."

Minute

Returns the number of minutes when called with the time. For example, Minute("23:50:45") returns 50.

Month

Returns the month when called with a date. For example, Month("4/1/1996") returns 4.

MsgBox

A message box can be displayed using the MsgBox command. The syntax of the MsgBox command is as follows:

MsgBox <MessageBoxPrompt>,<ButtonStyle>,<Title>

By replacing <ButtonStyle> with various values shown in Table 21.1, a message box can be customized using the following table. For example, an OK dialog box with a warning message icon can be created by replacing <ButtonStyle> with 48.

Table 21.1. Message Box codes.

Button Type
Button Description
0
OK
1
OK and Cancel
2
Abort, Retry, and Ignore
3
Yes, No, and Cancel
4
Yes and No
5
Retry and Cancel
16
Critical Message icon (Figure 21.8)
32
Warning Query icon (Figure 21.9)
48
Warning Message icon (Figure 21.10)
64
Information Message icon (Figure 21.11)
256
Second button is default
512
Third button is default
4096
All applications are stopped until the user responds to the message box

Figure 21.8: The Critical Message box.

Figure 21.9: The Warning Query box.

Figure 21.10: The Warning Message box.

Figure 21.11: The Information Message box.

Now

Returns the current date and time from the system clock. The return value is followed by the date and then the time. For example, the Now command returned the string 4/1/1996 23:08:31 at the time of this writing.

Oct

Returns the octal value (base 8) of a numerical expression. For example, Oct(10) returns 12.

Right

Returns a certain number of characters from the right side of a string. For example, Right("Windows NT", 2) returns NT.

Rnd

Returns a random number between 1 and 0. Be sure to seed the random number generator by calling Randomize before using the Rnd function.

Second

Returns the number of seconds of a date expression. For example, Second("18:23:57") returns 57.

Sgn

Returns the sign of a numerical expression. If the expression is 0, 0 is returned. If it is less than 0, -1 is returned. Otherwise, 1 is returned.

Sin

Returns the sine of an angle. For example, Sin (Pi) returns 0.

Sqr

Returns the square root of a nonnegative, numerical expression.

Str

Converts a numeric expression into a string and returns it.

StrComp

The syntax of the StrComp function is as follows.

StrComp (<String1>, <String2>, <ComparisonMethod>)

After StrComp compares both strings, it returns 0 if both strings are identical, -1 if <String1> is less than <STRING2>, and 1 otherwise. The <ComparisonMethod> argument is optional. If it is 0, a binary comparison is performed, and if it is 1, a case-insensitive comparison is performed. If <ComparisonMethod> is left out, a binary comparison is performed.

String

The String function is handy for repeating a character a certain number of times. For example, String(5,"*") can be used to create a string of five asterisks.

Tan

The Tan function can be used to calculate the tangent of an angle. For example, Tan (0) returns 0.

Time

Returns the current time from the system clock. For example, the value 01:23:48 was returned by the Time function at the time of this writing.

TimeSerial

This is a very handy function that can be used to perform various time calculations. For example, if the current time is 12:30, TimeSerial can be used to calculate the time 25 minutes ago. For example, TimeSerial(12,30-25, 0) returns 12:05:00.

TimeValue

Returns an expression passed into the function after converting it into a variant of subtype Date. For example, TimeValue ("2:35:17pm") returns 14:35:17.

UBound

UBound can be used to determine the maximum size of an array dimension. For example, if ArrayVariable is a three-dimensional array defined with the statement Dim ArrayVariable(100,200,300), UBound(ArrayVariable,1) returns 100, UBound(ArrayVariable,2) returns 200, and, of course, UBound(ArrayVariable,3) returns 300.

UCase

Converts strings passed into the function into uppercase and returns them. For example, UCase("Windows NT") returns WINDOWS NT.

Val

The Val function can be used to obtain a number contained in a string. The function scans the string until it encounters a character that is not part of a number. For example, Val(" 1234 567 in a string") returns the number 1234567.

VarType

The type of a variable can be determined using the VarType function. For example, if IntVariable was an Integer variable, VarType(IntVariable) will return 2. The type of a variable can be determined by examining the return value of VarType according to Table 21.2.

Table 21.2. Variable type codes.

Value Returned
Type of Variable
0
Empty
1
Null
2
Integer
3
Long integer
4
Single-precision, floating-point number
5
Double-precision, floating-point number
6
Currency
7
Date
8
String
9
OLE Automation object
10
Error
11
Boolean
12
Variant
13
Non-OLE Automation object
8192
Array

Weekday

The Weekday function returns a number between 1 and 7. The numbers returned by the
Weekday function correspond to the days of the week, as shown in Table 21.3.

Table 21.3. Day codes.

Day Code
Day of Week
1
Sunday
2
Monday
3
Tuesday
4
Wednesday
5
Thursday
6
Friday
7
Saturday

For example, Weekday("April 2, 1996") returns 3-which is, indeed, a Tuesday.

Year

Returns the year of the expression. For example, Year("February 29, 1976") returns 1976.

Applications of VBScript

Various control structures and commands that can be used to create VBScript programs were outlined in preceding sections. The last few sections will be devoted to applications of these commands and control structures to demonstrate how VBScript can be used create active Web pages.

Simple Calculator

Using various functions and control structures described earlier, a simple calculator can be created using VBScript. If you wish to experiment with the source code of the calculator program, it is included on the CD-ROM (\Chapter-21\Lesson2.htm). Shortly, you will learn how to create a calculator similar to the one shown in Figure 21.12.

Figure 21.12: The Simple Calculator application.

Operators and numbers can be entered into the calculator either by using numeric buttons shown in Figure 21.12 or simply typing them into one of the three text boxes. Before proceeding any further, it is recommended that you experiment with the calculator program and find out how it works. When the Simple Calculator Web page is first invoked and numbers are typed in using various command buttons, they appear in the left-hand text box. After a valid operator is entered into the operator text box, numbers entered next appear on the right-hand text box. At this point, if the Evaluate button is clicked, the VBScript program will evaluate the expression entered and return its value in a dialog box, as shown in Figure 21.13.

Figure 21.13: When the Evaluate button is pressed, the VBScript program calculates the expression entered and returns its value in a dialog box.

After the OK button in the dialog box shown in Figure 21.13 is pressed, the result of the calculation will be copied to the first text box, as shown in Figure 21.14. The user can then keep on performing calculations using the results of previous calculations.

Figure 21.14: The result of a calculation is copied to the first text box so that it can be used as part of another calculation.

Let's now examine the calculator program in detail and learn how it works. The following VBScript subroutine displays a dialog box similar to the one shown in Figure 21.15 when a user clicks on the About button. Note how the string-concatenation operator is used in line 4 to merge two strings.

Figure 21.15: The About dialog box.

1: Sub BtnAbout_OnClick
2:  titleString = "Web Site Developer's Guide for Windows NT"
3:  helloString = "Simple VBScript calculator by "
4:  helloString = helloString & "Sanjaya Hettihewa."
5:  MsgBox helloString, 64, titleString
6: End Sub

Error checking is an important part of any application. One of VBScript's strengths is its ability to perform various error checks when users enter data into a form. By using the OnChange event, it is possible to check the value of a text box that was recently changed by the user. The subroutine shown next makes sure the user entered a valid number into a text box that is used to obtain an operand from the user. The error-checking subroutine of the second operand is similar to the one shown next. Note how Chr(10) is used to create a multiline string. As you can see in Figure 21.16, when a user enters an invalid number, the following subroutine informs the user and resets the text box.

Figure 21.16: Invalid numbers entered by users are detected by the Operand1Box_OnChange subroutine.

 1: Sub Operand1Box_OnChange
 2:  IF (NOT IsNumeric(Operand1Box.Value)) THEN
 3:     MsgBoxString = "Do not type invalid characters "
 4:     MsgBoxString = MsgBoxString & "into the Results Window! "
 5:     MsgBoxString = MsgBoxString & chr(10)
 6:     MsgBoxString = MsgBoxString & "Results Window will now be reset."
 7:     MsgBox MsgBoxString , 48 , "Invalid input detected!"
 8:     Operand1Box.Value = 0
 9:  END IF
10: End Sub

A similar subroutine is used to check that operators entered into the operator text box are valid. The following code listing verifies that operators entered into the operator text box are valid. Note how the underline character (_) is used to join a long expression that spans several lines. If an invalid operator is entered, it is detected by OperatorBox_OnChange subroutine, the text box is reset, and the user is informed of the invalid input, as shown in Figure 21.17.

Figure 21.17: Invalid operators entered into the operator text box are detected by the OperatorBox_OnChange subroutine.

1: Sub OperatorBox_OnChange
 2:  IF (NOT((OperatorBox.Value = "+" ) OR _
 3:     (OperatorBox.Value = "-" ) OR _
 4:     (OperatorBox.Value = "*" ) OR _
 5:     (OperatorBox.Value = "?" ))) THEN
 6:     MsgString = "Do not type invalid characters "
 7:     MsgString = MsgString & "into the operator text box! "
 8:     MsgString = MsgString & chr(10)
 9:     MsgString = MsgString & "The operator text box will now be reset."
10:     MsgString = MsgString & chr(10) & chr(10)
11:     MsgString = MsgString & "Valid input: +, -, *"
12:     MsgBox MsgString , 48 , "Invalid input detected!"
13:     OperatorBox.Value = "?"
14:  END IF
15: End Sub

The Delete button is used to delete characters entered into one of the operand text boxes. The subroutine associated with the Delete button, BtnDelete_OnClick, is a smart function subroutine. As shown in line 2 of the following code listing, the subroutine first examines the operator text box and determines if a calculation has already been performed. If so, it knows that any numbers added appear on the text box to the right and deletes a digit from that text box. If not, a digit from the left text box is deleted.

 1: Sub BtnDelete_OnClick
 2:  IF (OperatorBox.Value = "?") THEN
 3:     IF ((Len (Operand1Box.Value) > 0) AND (Operand1Box.Value <> 0)) THEN
 4:        Operand1Box.Value = Left (Operand1Box.Value,  Len (Operand1Box.Value) -
1)
 5:     IF (Len (Operand1Box.Value) = 0) THEN
 6:        Operand1Box.Value = 0
 7:     END IF
 8:     END IF
 9:  ELSE
10:     IF ((Len (Operand2Box.Value) > 0) AND (Operand2Box.Value <> 0)) THEN
11:        Operand2Box.Value = Left (Operand2Box.Value,  Len (Operand2Box.Value) -
1)

12:     IF (Len (Operand2Box.Value) = 0) THEN
13:        Operand2Box.Value = 0
14:     END IF
15:     END IF
16:  END IF
17: End Sub

The Evaluate button calculates two operands using an operator and returns a value as shown in Figure 21.13. As you can see in line 2 of the following program listing, the BtnEvaluate_OnClick subroutine first checks the Operator text box. If a valid operator is found, it performs a calculation and displays it using a dialog box. If not, a dialog box similar to the one shown in Figure 21.18 is displayed. Afterwards, as shown in lines 17 and 18, the operand text boxes are reset so that additional calculations can be performed. Note that the result of the calculation is copied in line 17 to the left operand box so that the result of the calculation can be used as part of another calculation.

Figure 21.18: The operands are evaluated only if a valid operator is found.

 1: Sub BtnEvaluate_OnClick
 2:  IF (OperatorBox.Value = "?") THEN
 3:     MsgBoxString = "A valid operator is required to carry out "
 4:     MsgBoxString = MsgBoxString & "an evaluation."
 5:     MsgBoxString = MsgBoxString & chr(10)
 6:     MsgBoxString = MsgBoxString & "Valid operators are: +, -, *"
 7:     MsgBox MsgBoxString , 48 , "Invalid operator!"
 8:  ELSE
 9:     IF (OperatorBox.Value = "+")  THEN
10:        answer = CDbl(Operand1Box.Value) + CDbl(Operand2Box.Value)
11:     ELSEIF (OperatorBox.Value = "-")  THEN
12:        answer = CDbl(Operand1Box.Value) - CDbl(Operand2Box.Value)
13:     ELSEIF (OperatorBox.Value = "*")  THEN
14:        answer = CDbl(Operand1Box.Value) * CDbl(Operand2Box.Value)
15:     End IF
16:     MsgBox answer , 64 , "Results of calculation"
17:     Operand1Box.Value = answer
18:     Operand2Box.Value = 0
19:  END IF
20: End Sub

The AddDigit subroutine adds a digit selected via one of the calculator buttons into one of the operand text boxes. As shown in line 4 of the following program listing, if a valid operator is not present, digits are added to the left text box. However, if a valid operator is present, this means that the user has either entered a valid number to the left text box or that it contains the result of a previous calculation (in which case, the digit selected by the user is added to the right text box). When adding digits, there is a possibility that the user will try to add too many digits. This is taken care of in lines 9 and 16, where a separate subroutine is used to inform the reader by displaying a dialog box similar to the one shown in Figure 21.19.

Figure 21.19: The AddDigit subroutine prevents users from entering too many digits into a text box.

 1: Sub AddDigit ( digit )
 2:  REM Just in case there are any preceding zeros or spaces
 3:  Operand1Box.Value = CDbl (Operand1Box.Value)
 4:  IF ( OperatorBox.Value = "?") THEN
 5:     IF ( Len ( Operand1Box.Value ) < 14 ) THEN
 6:        Operand1Box.Value = Operand1Box.Value & digit
 7:        Operand1Box.Value = CDbl (Operand1Box.Value)
 8:     ELSE
 9:        TooManyDigits
10:     END IF
11:  ELSE
12:     IF ( Len ( Operand2Box.Value ) < 14 ) THEN
13:        Operand2Box.Value = Operand2Box.Value & digit
14:        Operand2Box.Value = CDbl (Operand2Box.Value)
15:     ELSE
16:        TooManyDigits
17:     END IF
18:  END IF
19: End Sub

For your reference, the full source code of the Calculator application is given in Listing 21.2.


Listing 21.2. The Calculator Web page.

<!--
(C) 1996 Sanjaya Hettihewa (http://wonderland.dial.umd.edu)
All Rights Reserved.
Permission is hereby given to modify and distribute this code
as you wish provided that this block of text remains unchanged.
!-->

<HTML>
<HEAD>
<TITLE>VBScript Tutorial: Simple Calculator</TITLE>
</HEAD>

<TABLE COLSPEC="L20 L20 L20" BORDER=2 WIDTH=10 HEIGHT=10>
<CAPTION ALIGN=top>Simple Calculator</CAPTION>
<TR><TD>
<BODY BGCOLOR="#FFFFFF" TEXT="#0000FF"
      LINK="#B864FF" VLINK="#670000" ALINK="#FF0000">
<IMG ALIGN=TOP SRC="vbscript.jpg">
<TD>

<TABLE BORDER=2 >
<CAPTION ALIGN=top>Results Window</CAPTION>
 <TD>
 <input type=text size=14 maxlength=14 name="Operand1Box" value="0">
 <input type=text size=1 maxlength=1 name="OperatorBox" value="?">
 <input type=text size=14 maxlength=14 name="Operand2Box" value="0">
 </TD>
</TABLE>

<TABLE COLSPEC="L20 L20 L20" >

<CAPTION ALIGN=top>Calculator Keys</CAPTION>
<TR>
 <TD><INPUT TYPE=BUTTON VALUE="One" NAME="BtnOne"></TD>
 <TD><INPUT TYPE=BUTTON VALUE="Two" NAME="BtnTwo"></TD>
 <TD><INPUT TYPE=BUTTON VALUE="Three" NAME="BtnThree"></TD>
</TR>
<TR>
 <TD><INPUT TYPE=BUTTON VALUE="Four" NAME="BtnFour"></TD>
 <TD><INPUT TYPE=BUTTON VALUE="Five" NAME="BtnFive"></TD>
 <TD><INPUT TYPE=BUTTON VALUE="Six" NAME="BtnSix"></TD>
</TR>
<TR>
 <TD><INPUT TYPE=BUTTON VALUE="Seven" NAME="BtnSeven"></TD>
 <TD><INPUT TYPE=BUTTON VALUE="Eight" NAME="BtnEight"></TD>
 <TD><INPUT TYPE=BUTTON VALUE="Nine" NAME="BtnNine"></TD>
</TR>
<TR>
 <TD><INPUT TYPE=BUTTON VALUE="Zero" NAME="BtnZero"></TD>
 <TD><INPUT TYPE=BUTTON VALUE="Backspace" NAME="BtnDelete></TD>
 <TD><INPUT TYPE=BUTTON VALUE="Clear" NAME="BtnClear"></TD>
</TR>
<TR>
 <TD><INPUT TYPE=BUTTON VALUE="+" NAME="BtnPlus"></TD>
 <TD><INPUT TYPE=BUTTON VALUE="-" NAME="BtnMinus"></TD>
 <TD><INPUT TYPE=BUTTON VALUE="*" NAME="BtnMultiply"></TD>
</TR>

<TR>
 <TD><INPUT TYPE=BUTTON VALUE="Evaluate" NAME="BtnEvaluate"></TD>
 <TD><INPUT TYPE=BUTTON VALUE="About" NAME="BtnAbout"></TD>
</TR>

</TABLE>

</TR>
</TABLE>

<P>

<B><FONT FACE="Comic Sans MS" SIZE=6 COLOR=RED>
VBScript Tutorial: <FONT></B>
<I><FONT FACE="Comic Sans MS" SIZE=5 COLOR=BLUE>
 "Simple Calculator" </I><P><FONT>


<SCRIPT LANGUAGE=VBS>
<!-- To hide VBScript code from technologically challenged browsers

Sub BtnAbout_OnClick
 titleString = "Web Site Developer's Guide for Windows NT"
 helloString = "Simple VBScript calculator by "
 helloString = helloString & "Sanjaya Hettihewa."
 MsgBox helloString, 64, titleString
End Sub

Sub Operand1Box_OnChange
 IF (NOT IsNumeric(Operand1Box.Value)) THEN
    MsgBoxString = "Do not type invalid characters "
    MsgBoxString = MsgBoxString & "into the Results Window! "
    MsgBoxString = MsgBoxString & chr(10)
    MsgBoxString = MsgBoxString & "Results Window will now be reset."
    MsgBox MsgBoxString , 48 , "Invalid input detected!"
    Operand1Box.Value = 0
 END IF
End Sub

Sub Operand2Box_OnChange
 IF (NOT IsNumeric(Operand2Box.Value)) THEN
    MsgBoxString = "Do not type invalid characters "
    MsgBoxString = MsgBoxString & "into the Results Window! "
    MsgBoxString = MsgBoxString & chr(10)
    MsgBoxString = MsgBoxString & "Results Window will now be reset."
    MsgBox MsgBoxString , 48 , "Invalid input detected!"
    Operand2Box.Value = 0
 END IF
End Sub

Sub OperatorBox_OnChange
 IF (NOT((OperatorBox.Value = "+" ) OR _
    (OperatorBox.Value = "-" ) OR _
    (OperatorBox.Value = "*" ) OR _
    (OperatorBox.Value = "?" ))) THEN
    MsgString = "Do not type invalid characters "
    MsgString = MsgString & "into the operator text box! "
    MsgString = MsgString & chr(10)
    MsgString = MsgString & "The operator text box will now be reset."
    MsgString = MsgString & chr(10) & chr(10)
    MsgString = MsgString & "Valid input: +, -, *"
    MsgBox MsgString , 48 , "Invalid input detected!"
    OperatorBox.Value = "?"
 END IF
End Sub

Sub BtnOne_OnClick
 IF (IsNumeric(Operand1Box.Value)) THEN
    AddDigit ( 1 )
 ELSE
    ResetResultsWindow
 END IF
End Sub
Sub BtnTwo_OnClick
 IF (IsNumeric(Operand1Box.Value)) THEN
    AddDigit ( 2 )
 ELSE
    ResetResultsWindow
 END IF
End Sub
Sub BtnThree_OnClick
 IF (IsNumeric(Operand1Box.Value)) THEN
    AddDigit ( 3 )
 ELSE
    ResetResultsWindow
 END IF
End Sub
Sub BtnFour_OnClick
 IF (IsNumeric(Operand1Box.Value)) THEN
    AddDigit ( 4 )
 ELSE
    ResetResultsWindow
 END IF
End Sub
Sub BtnFive_OnClick
 IF (IsNumeric(Operand1Box.Value)) THEN
    AddDigit ( 5 )
 ELSE
    ResetResultsWindow
 END IF
End Sub
Sub BtnSix_OnClick
 IF (IsNumeric(Operand1Box.Value)) THEN
    AddDigit ( 6 )
 ELSE
    ResetResultsWindow
 END IF
End Sub
Sub BtnSeven_OnClick
 IF (IsNumeric(Operand1Box.Value)) THEN
    AddDigit ( 7 )
 ELSE
    ResetResultsWindow
 END IF
End Sub
Sub BtnEight_OnClick
 IF (IsNumeric(Operand1Box.Value)) THEN
    AddDigit ( 8 )
 ELSE
    ResetResultsWindow
 END IF
End Sub
Sub BtnNine_OnClick
 IF (IsNumeric(Operand1Box.Value)) THEN
    AddDigit ( 9 )
 ELSE
    ResetResultsWindow
 END IF
End Sub
Sub BtnZero_OnClick
 IF (IsNumeric(Operand1Box.Value)) THEN
    AddDigit ( 0 )
 ELSE
    ResetResultsWindow
 END IF
End Sub

Sub BtnDelete_OnClick
 IF (OperatorBox.Value = "?") THEN
    IF ((Len (Operand1Box.Value) > 0) AND (Operand1Box.Value <> 0)) THEN
       Operand1Box.Value = Left (Operand1Box.Value,  Len (Operand1Box.Value) - 1)
    IF (Len (Operand1Box.Value) = 0) THEN
       Operand1Box.Value = 0
    END IF
    END IF
 ELSE
    IF ((Len (Operand2Box.Value) > 0) AND (Operand2Box.Value <> 0)) THEN
       Operand2Box.Value = Left (Operand2Box.Value,  Len (Operand2Box.Value) - 1)
    IF (Len (Operand2Box.Value) = 0) THEN
       Operand2Box.Value = 0
    END IF
    END IF
 END IF
End Sub

Sub BtnClear_OnClick
 Operand1Box.Value = 0
 Operand2Box.Value = 0
 OperatorBox.Value = "?"
End Sub

Sub BtnPlus_OnClick
 OperatorBox.Value = "+"
End Sub

Sub BtnMinus_OnClick
 OperatorBox.Value = "-"
End Sub

Sub BtnMultiply_OnClick
 OperatorBox.Value = "*"
End Sub

Sub BtnEvaluate_OnClick
 IF (OperatorBox.Value = "?") THEN
    MsgBoxString = "A valid operator is required to carry out "
    MsgBoxString = MsgBoxString & "an evaluation."
    MsgBoxString = MsgBoxString & chr(10)
    MsgBoxString = MsgBoxString & "Valid operators are: +, -, *"
    MsgBox MsgBoxString , 48 , "Invalid operator!"
 ELSE
    IF (OperatorBox.Value = "+")  THEN
       answer = CDbl(Operand1Box.Value) + CDbl(Operand2Box.Value)
    ELSEIF (OperatorBox.Value = "-")  THEN
       answer = CDbl(Operand1Box.Value) - CDbl(Operand2Box.Value)
    ELSEIF (OperatorBox.Value = "*")  THEN
       answer = CDbl(Operand1Box.Value) * CDbl(Operand2Box.Value)
    End IF
    MsgBox answer , 64 , "Results of calculation"
    Operand1Box.Value = answer
    Operand2Box.Value = 0
 END IF
End Sub

Sub AddDigit ( digit )
 REM Just in case there are any preceeding zeros or spaces
 Operand1Box.Value = CDbl (Operand1Box.Value)
 IF ( OperatorBox.Value = "?") THEN
    IF ( Len ( Operand1Box.Value ) < 14 ) THEN
       Operand1Box.Value = Operand1Box.Value & digit
       Operand1Box.Value = CDbl (Operand1Box.Value)
    ELSE
       TooManyDigits
    END IF
 ELSE
    IF ( Len ( Operand2Box.Value ) < 14 ) THEN
       Operand2Box.Value = Operand2Box.Value & digit
       Operand2Box.Value = CDbl (Operand2Box.Value)
    ELSE
       TooManyDigits
    END IF
 END IF
End Sub

Sub ResetResultsWindow
 MsgBoxString = "Do not type invalid characters "
 MsgBoxString = MsgBoxString & "into the Results Window! "
 MsgBoxString = MsgBoxString & chr(10)
 MsgBoxString = MsgBoxString & "Use Calculator keys instead. "
 MsgBoxString = MsgBoxString & "Results Window will now be reset."
 MsgBox MsgBoxString , 48 , "Invalid input detected!"
 Operand1Box.Value = 0
 Operand2Box.Value = 0
 OperatorBox.Value = "?"
End Sub

Sub TooManyDigits
 MsgBoxString = "The number of digits you have typed "
 MsgBoxString = MsgBoxString & "exceed the maximum"
 MsgBoxString = MsgBoxString & chr(10)
 MsgBoxString = MsgBoxString & "number of digits allowed. "
 MsgBoxString = MsgBoxString & "The digit you selected will "
 MsgBoxString = MsgBoxString & "not be added. Sorry!"
 MsgBox MsgBoxString , 48 , "Too many digits!"
End Sub

!-->
</SCRIPT>

</BODY>
</HTML>

Labeling an Image

VBScript can be used to label a graphic when the mouse is moved over it. The VBScript program listed shortly can be used to label an image. When the Web page containing the VBScript program is first invoked, it looks similar to Figure 21.20. Note the string Hello! Select a link, please. is contained in the description text box.

Figure 21.20: Text box contains the string Hello! Select a link, please. when the VBScript Web page is first invoked.

At this point, if the mouse is moved over the graphic in Figure 21.20, the value of the text box changes.

As you can see in Figure 21.22, there are four icons in the graphic to the left of the browser window. When the mouse is moved over any of these icons, the text box will list the description of the text box. For example, when the mouse is over the bulletin-board icon, the value of the text box in Figure 21.21 changes to Post messages on an online discussion forum. Various key subroutines of the label-image program will be discussed next.

Figure 21.21: When the mouse is moved over the graphic, the value of the text box changes to No link selected. Please select a link.

Figure 21.22: When the mouse is over one of the icons of the image, the value of the text box changes the icon's description.

In order to detect mouse movement over the graphic in Figure 21.22, a special identification code needs to be assigned to the graphic. This is done in line 1 of the following code listing:

1: <A ID="ImageMapGraphic" HREF="ImageMap.Map">
2: <IMG  ALIGN=TOP SRC="vbscript.jpg" ALT="Sample Graphic" ISMAP BORDER=0>
3: </A>

The ImageMapGraphic_MouseMove is the heart of the VBScript shown in Figure 21.22. When the mouse is moved over the graphic, the following subroutine is activated. When the mouse pointer falls in a predetermined region of the graphic, the text box is updated with the description of the region the mouse pointer is over, as shown in line 4 of the following program listing. The HotSpot subroutine simply returns TRUE if the mouse coordinates passed into the HotSpot subroutine fall within a certain region of the graphic.

 1: Sub ImageMapGraphic_MouseMove(keyboard,mouse,xPosition,yPosition)
 2:
 3: IF (HotSpot(xPosition, yPosition,  2, 5, 70, 41)) THEN
 4:   Description.Value = "Main Homepage"
 5: ELSE IF (HotSpot(xPosition, yPosition,  2, 49, 70, 82)) THEN
 6:   Description.Value = "Send Feedback"
 7: ELSE IF (HotSpot(xPosition, yPosition,  2, 84, 70, 117)) THEN
 8:   Description.Value = "Site Map"
 9: ELSE IF (HotSpot(xPosition, yPosition,  2, 119, 70, 164)) THEN
10:   Description.Value = "Post messages on an online discussion forum"
11: ELSE
12:   Description.Value = "No link selected. Please select a link!"
13: END IF
14: END IF
15: END IF
16: END IF

If you would like to experiment with the VBScript program listed next, it can be found on the CD-ROM (\Chapter-21\Lesson3.htm) that accompanies this book. For your reference, the full source code of the Label Image application is given in Listing 21.3.


Listing 21.3. Labeling a graphic.

<!--
(C) 1996 Sanjaya Hettihewa (http://wonderland.dial.umd.edu)
All Rights Reserved.
       Permission is hereby given to modify and distribute this code as you wish provided that this block of text remains unchanged.
!-->

<HTML>
<HEAD>
<TITLE>VBScript Tutorial: Labeling a graphic</TITLE>
</HEAD>

<BODY BGCOLOR="#FFFFFF" TEXT="#0000FF"
            LINK="#B864FF" VLINK="#670000" ALINK="#FF0000">

<TABLE COLSPEC="L20 L20 L20" BORDER=2 WIDTH=10 HEIGHT=10>
<CAPTION ALIGN=top>Labeling a graphic</CAPTION>
<TR><TD>

<A ID="ImageMapGraphic" HREF="ImageMap.Map">
<IMG  ALIGN=TOP SRC="vbscript.jpg" ALT="Sample Graphic" ISMAP BORDER=0>
</A>

</TD><TD>

<CENTER><FONT FACE="Comic Sans MS" SIZE=6 COLOR=Black>
Description<FONT></CENTER>
<input type="text" name="Description"
       Value="Hello! Select a link, please." size=45><P>

<CENTER><INPUT TYPE=BUTTON VALUE="About" NAME="BtnAbout"></CENTER>

</TD><TD>

</TR>
</TABLE>

<P>

<B><FONT FACE="Comic Sans MS" SIZE=6 COLOR=RED>
VBScript Tutorial: <FONT></B>
<I><FONT FACE="Comic Sans MS" SIZE=5 COLOR=BLUE>
 "Labeling a graphic with VBScript" </I><P><FONT>
</TD></TR>
</TABLE>

<SCRIPT LANGUAGE="VBS">
<!--  To hide VBScript code from  technologically challenged browsers

Sub BtnAbout_OnClick
  titleString = "Web Site Developer's Guide for Windows NT"
  helloString = "Labeling a graphic with VBScript by "
  helloString = helloString & "Sanjaya Hettihewa."
  MsgBox helloString, 64, titleString
End Sub

Sub ImageMapGraphic_MouseMove(keyboard,mouse,xPosition,yPosition)

IF (HotSpot(xPosition, yPosition,  2, 5, 70, 41)) THEN
  Description.Value = "Main Homepage"
ELSE IF (HotSpot(xPosition, yPosition,  2, 49, 70, 82)) THEN
  Description.Value = "Send Feedback"
ELSE IF (HotSpot(xPosition, yPosition,  2, 84, 70, 117)) THEN
  Description.Value = "Site Map"
ELSE IF (HotSpot(xPosition, yPosition,  2, 119, 70, 164)) THEN
  Description.Value = "Post messages on an online dicussion forum"
ELSE
  Description.Value = "No link selected. Please select a link!"
END IF
END IF
END IF
END IF

End Sub

Function HotSpot ( mouseX, mouseY, TopX , TopY, BottomX, BottomY)
 HotSpot = (mouseX >= TopX) AND _
           (mouseX <= BottomX) AND _
           (mouseY >= topY) AND _
           (mouseY<=bottomY)
End Function

!-->
</SCRIPT>

</BODY>
</HTML>

Summary

VBScript, a subset of Visual Basic, is an easy-to-use scripting language that can be used to create active Web pages. It enables Web-site developers to create various client-side solutions and make a Web site easier and more interesting to navigate.

What's Next?

A Web site's success depends on how well it is publicized on the Internet. The next chapter will discuss various ways of publicizing a Web site on the Internet to attract more visitors to it. As you will learn shortly, in addition to traditional information-distribution mediums such as newspapers, newsletters, television, magazines, and so on, a Web site can be publicized on the Internet using newsgroups, mail lists, and various Web-site cataloging databases.