Microsoft's Visual Basic, Scripting Edition (or simply, 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. Because VBScript is a Microsoft product, in the near future, you will also see a
great deal of VBScript/Windows NT/95/Moofice/Backoffice 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 Explorerspecifically, browsers from Oracle, Spyglass, and
NetManage.
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 latest information about VBScript.
http://www.microsoft.com/VBScript
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 31.1.
Figure 31.1. How VBScript works.
As you can see in Figure 31.1, a VBScript program is part of a regular HTML file and is enclosed between the 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 31.2.
Figure 31.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 in the
following:
<SCRIPT LANGUAGE=VBS> <!-- To hide VBScript code from technologically challenged browsers ... VBScript code !--> </SCRIPT>
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 31.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 31.3. The classic Hello World! application written with VBScript.
If you would like to experiment with the VBScript application shown in Figure 31.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.
As shown in Figure 31.4, the Hello World! dialog box is shown each time a user clicks on the Please click here for message box button in Figure 31.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 31.3, the Web browser invokes the BtnHello_OnClick subroutine and any VBScript code defined in that subroutine is executed.
The BtnHello_OnClick subroutine is a very simple VBScript subroutine. The first three lines create strings displayed by the dialog box in Figure 31.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 31.4.
NOTE
Line numbers in various code segments are not part of the VBScript code. The line numbers are there only 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
Figure 31.4. The Hello World! 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 31.5, line 3 of the following program listing displays the current time in a 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
Figure 31.5. The Time dialog box.
The date dialog box displays the current date in a dialog box, as shown in Figure 31.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).
1: Sub BtnDate_OnClick 2: dateString = "Today's date is " & DateValue(date) 3: MsgBox dateString , 0, "Date Dialog Box" 4: End Sub
Figure 31.6. The Date dialog box.
For your reference, the full source code of the Hello World! application is shown in Listing 31.1.
Listing 31.1. The Hello World! Web page.
<!--
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 supports several operators for various string, Boolean ,and number-manipulation tasks. Various operators supported by VBScript are listed next.
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.
Syntax: <operand1> - <operand2> Syntax: -<OperandToNegate>
The subtraction operator is used as 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.
Syntax: <operand1> ^ <operand2>
The multiplication operator takes two numeric operands, multiplies them, and returns the resulting value.
Syntax: <operand1> ^ <operand2>
The exponential operator returns the resulting value of <operand1> raised to the <operand2> power.
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.
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
Syntax: <operand1> & <operand2>
The string-concatenation operator can be used to join <operand1> and <operand2> together.
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 want to experiment with this operator, refer to
\Chapter-21\Mod.htm on the CD-ROM that accompanies this book. 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
VBScript supports several Boolean operators. The best way to explain how Boolean operators work is with a truth table. Refer to Figure 31.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 31.7. Truth tables of VBScript Boolean operators.
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.
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.
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.
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> must 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.
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 can be replaced with binary 1 and FALSE can be replaced with binary 0.
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.
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.
Syntax: <operand1> = <operand2>
This operator 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.
Syntax: <operand1> <> <operand2>
The unequal operator 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.
Syntax: <operand1> < <operand2>
This expression returns true if <operand1> is less than <operand2>. However, if either <operand1> or <operand2> is NULL, the less-than operator will return NULL.
Syntax: <operand1> <= <operand2>
This expression 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.
Syntax: <operand1> > <operand2>
This expression returns true if <operand1> is greater than <operand2>. However, if either <operand1> or <operand2> is NULL, the greater-than operator will return NULL.
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.
Control structures are an important part of any language. They give a language "life" by enabling 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 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.
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.
Syntax: Dim <VariableName1> , <VariableName2>
This statement can be used to declare variables of variant type. As shown here, you can define several variables at the same time by separating them with commas.
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.
Single Dimension Array Syntax: Dim <NameOfArray>(50)
You can use the Dim statement 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.
If you are unsure about the size of an array when it is first declared, VBScript enables you to create dynamic arrays. Dynamic arrays can be expanded or reduced as needed. You can create dynamic arrays 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, you do this 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.
You use the Do/Loop control structure 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> can 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.
Syntax: Erase <NameOfArray>
You use the Erase statement 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.
The Exit statement causes program control to be transferred out of the control structure in which it is used. The control structure can be a loop or a subroutine. Various forms of the Exit command are listed next.
You can use the For/Next control structure 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:
Note that the Exit For statement can be used to exit a For loop.
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.
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.
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
You create a function by replacing various labels of the preceding definition with values listed next.
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; procedures created with the Sub statement cannot.
You use the If/Then/Else statement 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.
You use the Let command 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 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 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:
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.
By preceding a variable declaration with the Private keyword, it is possible to limit its scope to the script in which it was declared.
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.
The Rem command is used to document VBScript code. The following is the syntax of the Rem command:
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.
The following is the syntax of the RSet command:
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.
The Set command can be used to assign an object reference to a variable or property. The following is the syntax of the Set command:
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>.
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.)
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
following is the syntax of the Sub statement. Note that the Exit Sub statement can be used to transfer control out of a procedure.
<ProcedureType> Sub <NameOfProcedure> <ArgumentsOfProcedure> ... VBScript statements End Sub
You can create a procedure by replacing various labels of the preceding definition with values listed next:
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
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.
The Abs function can be used to obtain the absolute value of a number. For example, Abs(-30) = 30 = Abs(30).
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 arc tangent 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.
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 is 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 is a handy function that can be used to calculate various days. By using numerical expressions, using the DateSerial function, it is possible to count back 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.
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.
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 preceding 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>
Both Int and Fix convert numerical expressions into integers. The only difference between the two 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 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 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 non-negative, numerical expression.
These eliminate spaces from a string and return 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.
A message box can be displayed using the MsgBox command. The syntax of the MsgBox command is
MsgBox <MessageBoxPrompt>,<ButtonStyle>,<Title>
By replacing <ButtonStyle> with various values shown in Table 31.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.
| 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 (see Figure 31.8) |
| 32 | Warning Query icon (see Figure 31.9) |
| 48 | Warning Message icon (see Figure 31.10) |
| 64 | Information Message icon (see Figure 31.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 31.8. The Critical Message dialog box.
Figure 31.9. The Warning Query dialog box.
Figure 31.10. The Warning Message dialog box.
Figure 31.11. The Information Message dialog 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 non-negative, numerical expression.
Str converts a numeric expression into a string and returns it.
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.
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.
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.
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 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 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 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.
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.
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 31.2.
| 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 |
The Weekday function returns a number between 1 and 7. The numbers returned by the Weekday function correspond to days of the week, as shown in Table 31.3.
| 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 3which is, indeed, a Tuesday.
Year returns the year of the expression. For example, Year("February 29, 1976") returns 1976.
Various control structures and commands that can be used to create VBScript programs were outlined in preceding sections. The last few sections are devoted to applications of these commands and control structures to demonstrate how VBScript can be used
to create active Web pages.
Using various functions and control structures described earlier, you can create a simple calculator using VBScript. If you want 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 31.12.
You can enter operators and numbers into the calculator either by using numeric buttons shown in Figure 31.12 or simply typing them into one of the three text boxes. Before proceeding any further, experiment with the calculator program and find out how
it works. When the Simple Calculator Web page is first invoked, and you type in numbers using various command buttons, they appear in the left-hand text box. When you enter a valid operator into the operator text box, numbers entered next appear in the
right-hand text box. At this point, if you click the Evaluate button, the VBScript program will evaluate the expression entered and return its value in a dialog box, as shown in Figure 31.13.
Figure 31.13. When the Evaluate button is pressed, the VBScript program calculates the expression entered and returns its value in a dialog box.
When you press the OK button in the dialog box shown in Figure 31.13, the result of the calculation is copied to the first text box, as shown in Figure 31.14. The user can then keep on performing calculations using results of previous calculations.
Figure 31.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 31.15 when a user clicks the About button. Note how the string-concatenation operator
is used in line 4 to merge two strings.
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
Figure 31.15. The About dialog box.
Error checking is an important part of any application. One of VBScript's strengths is its capability 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 31.16, when a user enters an invalid number, the following subroutine informs the user and resets the text box.
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
Figure 31.16. Invalid numbers entered by users are detected by the Operand1Box_OnChange subroutine.
A similar subroutine is used to check whether 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 the OperatorBox_OnChange subroutine, the text box is reset, and the user is informed of the invalid input, as shown in Figure 31.17.
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
Figure 31.17. Invalid operators entered into the operator text box are detected by the OperatorBox_OnChange subroutine.
You use the Delete button 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 31.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 31.18 is displayed. Afterward, 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.
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
Figure 31.18. The operands are evaluated only if a valid operator is found.
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 a 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 31.19.
1: Sub AddDigit ( digit ) 2: REM Just in case there are any preceeding 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
Figure 31.19. The AddDigit subroutine prevents users from entering too many digits into a text box.
For your reference, the full source code of the Calculator application is given in Listing 31.2.
Listing 31.2. The Calculator Web page.
<!--
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>
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 31.20. Note the
description text box contains the string Hello! Select a link, please.
Figure 31.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 31.21, the value of the text box changes.
Figure 31.21. When the mouse is moved over the graphic, the value of the text box changes to No link selected. Please select a link!.
As you can see in Figure 31.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 31.21 changes to Post messages on an online discussion forum. Various key subroutines of the label-image program are discussed next.
Figure 31.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 31.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 31.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 dicussion 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 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 31.3.
Listing 31.3. Labeling a graphic.
<!--
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>
The ActiveX Control Pad is a useful application for inserting ActiveX controls into Web pages. With it, you can create richly interactive multimedia Web pages using an easy-to-use graphical user interface. This section focuses on how the ActiveX
Control
Pad can be used to insert ActiveX controls into Web pages. Although the following example performs a very simple task, it demonstrates how the ActiveX Control Pad can be used to automate ActiveX controls using VBScript. For additional information about
VBScript programming with the ActiveX Control Pad, visit
http://WWW.NetInnovation.com/
This exercise demonstrates how the ActiveX Control Pad can be used to create a clock. Before proceeding any further, downloaded and install the ActiveX Control Pad on your system. The ActiveX Control Pad can be downloaded from
http://www.microsoft.com/intdev/author/cpad/
After you install the ActiveX Control Pad, invoke it by executing the "Microsoft ActiveX Control Pad" icon located in the "Microsoft ActiveX Control Pad" Start Menu folder. When it is first invoked, the ActiveX Control Pad looks
similar to the Window in Figure 31.23.
Figure 31.23. The ActiveX Control Pad.
In order to create the clock, two ActiveX controls (the Microsoft Forms 2.0 Label and the Timer Object) have to be inserted into the Web page in Figure 31.24. The Microsoft Forms 2.0 Label displays the time and the Timer Object updates the Microsoft
Forms 2.0 Label each second. These two controls can be inserted by selecting Edit | Insert ActiveX Control from the menu bar and using the Insert ActiveX Control dialog box (see Figure 31.24).
Figure 31.24. The Insert ActiveX Control dialog box is used to insert ActiveX controls to Web pages.
Note
When you are inserting ActiveX controls, make sure the cursor is between the two HTML tags <BODY> and </BODY> before invoking the dialog box in Figure 31.24.
When you insert the two ActiveX controls, Microsoft Forms 2.0 Label and Timer Object, you will see a Properties dialog box for each ActiveX control. Change values of the Properties dialog box of the Microsoft Forms 2.0 Label ActiveX Control to match
the
values of the dialog box in Figure 31.25. Similarly, modify values of the Properties dialog box of the Timer Object to match the values of the dialog box in Figure 31.26. After you modify the values, click the Cancel button of each dialog box, which is
located in the top-right corner.
Figure 31.25. Values of the Properties dialog box of the Microsoft Forms 2.0 Label ActiveX Control.
Figure 31.26. Values of the Properties dialog box of the Timer Object ActiveX control.
After you insert the two ActiveX controls, they need to be automated with VBScript. You use the Script Wizard to do this. Select Tools | Script Wizard to invoke the Script Wizard dialog box shown in Figure 31.27. If this dialog box looks somewhat
complicated, do not worry; it is very easy to use. After you understand how it works, you will love the Script Wizard. As you can see in Figure 31.27, the top half of the Script Wizard is comprised of two frames. The left frame contains various events and
the right frame contains various actions of ActiveX controls that have been inserted into the Web page being edited.
Because the clock has to be updated each second, select the Timer event of the IeTimer1 object in the left frame as shown in Figure 31.27. Afterward, select the caption attribute of the Label1 object as illustrated in Figure 31.27.
Figure 31.27. The Script Wizard is used to assign actions to various events of ActiveX controls.
Press the Insert Action Button. The dialog box in Figure 31.28 appears. This dialog box is used to assign a value to the caption of the Label1 object each time the Timer action is triggered.
Figure 31.28. Change Label1 Caption dialog box (used to type in string expressions).
Because the caption of Label1 has to be updated with the value of a VBScript function that returns the current system time, press the Custom button of the dialog box in Figure 31.28. The Change Label1 Caption dialog box shown in Figure 31.29 appears.
Type Time, the name of the VBScript function that returns the current time, in the Change Label1 Caption dialog box and press the OK button. Afterward, press the OK button of the Script Wizard dialog box shown in Figure 31.27. Refer to Listing 31.4 for
the
Web page that was just created with the ActiveX Control Pad.
Figure 31.29. Change Label1 Caption dialog box (used to type in VBScript expressions).
Listing 31.4. HTML code of the ActiveX/VBScript Clock application.
<HTML>
<HEAD>
<TITLE>New Page</TITLE>
</HEAD>
<BODY>
<OBJECT ID="Label1" WIDTH=137 HEIGHT=31
CLASSID="CLSID:978C9E23-D4B0-11CE-BF2D-00AA003F40D0">
<PARAM NAME="ForeColor" VALUE="0">
<PARAM NAME="BackColor" VALUE="14286843">
<PARAM NAME="Size" VALUE="3620;811">
<PARAM NAME="SpecialEffect" VALUE="1">
<PARAM NAME="FontHeight" VALUE="360">
<PARAM NAME="FontCharSet" VALUE="0">
<PARAM NAME="FontPitchAndFamily" VALUE="2">
</OBJECT>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub IeTimer1_Timer()
Label1.Caption = Time
end sub
-->
</SCRIPT>
<OBJECT ID="IeTimer1" WIDTH=39 HEIGHT=39
CLASSID="CLSID:59CCB4A0-727D-11CF-AC36-00AA00A47DD2">
<PARAM NAME="_ExtentX" VALUE="1005">
<PARAM NAME="_ExtentY" VALUE="1005">
<PARAM NAME="Interval" VALUE="1000">
</OBJECT>
</BODY>
</HTML>
Note how the HTML code of Listing 31.4 appears in the ActiveX Control Pad. As you can see in Figure 31.30, a button is present in the left margin next to the VBScript code and each of the two ActiveX controls. To modify attributes of the ActiveX
controls or assign additional events and actions, press one of the buttons in the left margin.
Select File | Save to save the ActiveX/VBScript Clock application. After it is saved, it can be viewed with any Web browser that supports ActiveX, such as Internet Explorer, as shown in Figure 31.31.
Figure 31.31. ActiveX/VBScript Clock application.
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.
A Web site's success depends on how well it is publicized on the Internet. The next chapter discusses 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.