Previous Page TOC Next Page



Chapter 8


VBScript


by Jon Czernel


Microsoft has for years pushed BASIC as the de facto, entry-level development standard in the personal computer arena. In fact, the origins of the Microsoft empire can be traced back to its early adoption and development of BASIC for the first personal computers available. Many developers today, in fact, will say that one of the several Microsoft BASIC products were responsible for their entry into the development arena, either by hobby, profession, or both.

VBScript continues Microsoft's support of a language that has evolved into a fairly powerful development tool. Microsoft has announced that it will allow third parties to use VBScript as the scripting engine in their applications, and it has openly encouraged third parties to port VBScript to "alternative" (non-Windows) platforms through purchase of their VBScript source code.

This chapter examines the fundamental language constructs of VBScript, a strict subset of Visual Basic 4.0 (VB) and Visual Basic for Applications (VBA). In particular, the later sections of this chapter concentrate on the use of VBScript in HTML documents in conjunction with ActiveX Controls. For the sake of brevity, the authors assume that the reader has some development experience in at least one structured development language, such as VB, C/C++, or Object Pascal. Instead of concentrating on syntax, the chapter presents real-world VBScript examples wherever appropriate. The authors also assume that the reader has experience in basic HTML development and is familiar with the concept of ActiveX (OLE/OCX) controls.

This chapter is broken down into the following areas:

Note


The complete richness of VBScript is impossible to reveal in a single chapter. For more information on VBScript, refer to the Microsoft VBScript Web site at: http://www.microsoft.com/vbscript.

May your adventures in VBScript be both challenging and fulfilling! The first section begins with a discussion of VBScript fundamentals.

Language Fundamentals


This section discusses the fundamental architecture of VBScript. This section should be used as both a quick language reference and brief language tutorial. Like most language references, the section begins with the most basic elements, and then works its way up to larger, more encompassing constructs.

The VBScript Data Type: Variant


Unlike most other languages, VBScript allows only one data type: variant. A variant is a variable type that can hold any type of fundamental data type, including integers, floating points, characters, strings, and date/time values. Variant data types may also represent instances of objects.

With variants, you don't have to worry about ensuring that your variable is adequately prepared to handle unexpected data. However, although the variable itself might be able to contain any type of data, your routines will often be required to check for the type of data that is stored in a variable to ensure proper script execution.

VBScript assigns a subtype to variables dynamically during program execution. This subtype classification flags the variable as containing a particular type of value, such as an integer or a string. VBScript also includes the function VarType, and functions such as IsArray(), IsDate() and IsEmpty(), that enable you to determine, at runtime, the currently assigned subtype of a variable.

Table 8.1 enumerates the variant subtypes available, and the value returned by the VarType function when a variable of the given subtype is passed as a parameter. Alternative methods of determining a variable subtype, such as IsEmpty() or IsDate(), are also mentioned.

Table 8.1. Common variant subtypes and descriptions.

Variant VarType Explanation
Subtype Empty 0 Used to indicate an uninitialized variable or a zero-length string. See also: IsEmpty(). Null 1 Used when a variable has been assigned a Null value. See also: IsNull(). Boolean 11 Either True (–1) or False (0). Byte 17 An integer from 0 to 255. See also: IsNumeric(). Integer 2 An integer from –32768 to 32767. See also: IsNumeric(). Long Integer 3 An integer from –2,147,483,648 to 2,147,483,647. See also: IsNumeric(). Single 4 A floating-point value from –3.402823E38 to –1.401298E-45, 0, or 1.401298E-45 to 3.402823E38. See also: IsNumeric(). Double 5 A double precision floating-point number from –1.79769313486232E308 to –4.94065645841247E-324, or 4.94065645841247E-324 to 1.79769313486232E308. See also: IsNumeric(). Date/Time 7 A valid date/time value. See also: IsDate(). Date/Time values may be enclosed in quotes, such as "8/30/96" or in pound characters, such as #08/30/96#. String 8 A variable length string. Strings are enclosed in quotes, such as "Howdy". Object 9 An instance of an automation object. See also IsObject(). Object 13 An instance of an non-automation object. See also: IsObject().

Note that a variable subtype is dynamic during code execution, and it may change as code is executing, depending on the contents of the variable. For this reason, VBScript also includes mechanisms that enable you to convert (cast) a variant variable from one subtype to another. Table 8.2 lists some of the most important conversion functions built into VBScript.

Table 8.2. Variant conversion functions.

Function: Returns Asc() The ASCII code for the first character in the given string. CBool() A Boolean. CByte() A Byte. CDate() A Date/Time. CDbl() A Double Precision number. Chr() The character represented by the given ASCII code. CInt() An integer. CLng() A long integer. CSng() A single precision floating-point value. Hex() The hexadecimal representation of the given number, in string format.
Oct() The octal representation of a given number, in string format.

Warning

Remember that although variants provide a great deal of flexibility, it is still possible to raise type mismatch errors at runtime by casting a variable that contains an invalid value for the specified cast operation. For example, the function CDate will produce a type mismatch error if T contains anything besides a valid date/time value, such as "SomeGuyNamedJoe". Before forcing a variable cast, ensure that the variable you'll be casting contains a valid argument by using one of the Is.. functions, such as IsDate().


Variable Naming Rules


Variable names must conform to the following rules:

  1. 1. A variable name must begin with an alphabetic character. The remainder of the name may contain any alphanumeric characters, including underscores ("_").
  2. 2. The length of a variable cannot exceed 255 characters.
  3. 3. Periods may not be embedded in a variable name.
  4. 4. A variable name must be unique within the scope in which it is defined.

Variable Declarations


Variables in VBScript are declared explicitly using the Dim statement. Variables that are not explicitly declared are implicitly declared when they are first encountered in any statement.

Tip


It is best to explicitly declare your variables before they are used for the first time, as opposed to allowing VBScript to implicitly declare them when they are first used. Explicit declaration makes your code easier to debug and maintain. To force explicit declaration of variables, include the statement Option Explicit at the beginning of each script block.

The following block of code illustrates the declaration of several variables in VBScript:


...

Dim NewName

Dim ReturnValue, CalculatedValue

...

The scope of variables within an HTML document is discussed later in this chapter, in the section "VBScript Scoping Rules in HTML."

Tip


During this discussion of variables, no mention has been made so far of constants. This is for a good reason; there is no special provision for constants in VBScript. To implement constants, simply use standard variables. It is recommended, however, that you adhere to a specific naming convention when using a variable as a constant, such as ensuring that the entire variable name is capitalized, so that constants can be easily distinguished from regular variables.


Variable Assignments


To assign a value to a variable, a single equal sign is used, in the format <variable> = <value>.

Interestingly, unlike most other languages, in VBScript the assignment operator is the same as the equivalency operator. The following block of script illustrates several different data types being assigned to variables:


...

Dim SomeValue, ReturnDate

SomeValue = 32.22     'Begin with a floating point.

SomeValue = "Howdy"   'Since this is a variant, we can

                      'dynamically change its type.

ReturnDate = "9/1/98"

...

Arrays in VBScript


This discussion of variables in VBScript ends with the creation and assignment of arrays in VBScript. Arrays are declared using either the Dim or ReDim statement, as shown in the following block of code:


...

Dim Lookup(30), AnotherLookup(10,10,2)  'Static arrays

Dim Reference()       'Dynamic array declaration

Redim NewReference()  'Another Dynamic array declaration

...

Redim Reference(30), NewReference(10)  'Set a new size to these dynamic arrays

...

Redim NewReference(10)        'Set a new size for this array

Redim Preserve Reference(40)  'Set a new size for this array,

                              'preserving its previous contents

...

Referring to the preceding snippet, note the following points:

Note


In all arrays, each dimension begins with element zero (0). In the example Dim Test(5), six indices are actually created, from Test(0) to Test(5). As a further note, the Microsoft online documentation for VBScript, as of this writing, incorrectly states that the upper bound of a dimensioned array is equal to the specified array size minus one.

Tip


The variant subtype of an array is the same for all elements in an array. To determine the subtype of an array, you can use the VarType() function, and subtract 8192. This seemingly arbitrary subtraction will yield the "base" subtype number, as described earlier in Table 8.1.


Operators


VBScript provides all of the standard operators that you would expect in a development environment. Tables 8.3 through 8.5 list all operators used in VBScript, listed in order of precedence.

Table 8.3. Arithmetic operators.

Operator Name Example ^ Exponentiation A = B ^ 2 - Unary Negation A = –-B
Places the negation of B into A * Multiplication A = B * 33 / Division A = B / 2 \ Integer Division A = B / 2
Stores the Integer portion of
the division in A Mod Modulo A = B Mod 2
Stores the remainder of B/ 2
in A + Addition A = B + C - Subtraction A = B – C & String Concatenation A = B & C
Use of Addition operator
obtains the same result; use &
for code clarity.

Table 8.4. Comparison operators.

Operator Name Example = Equality If A = B then print "Equal" <> Inequality If A <> B then print "Not Equal" < Less Than If A < B then print "Less Than" > Greater Than If A > B then print "Greater Than" <= Less Than Or Equal To If A <= B then print "LTOE" >= Greater Than Or Equal To If A >= B then print "GTOE" Is Object Equivalency If A is B then print "Same"
Used to determine if two variables refer to the same object.

Table 8.5. Logical operators.

Operator Name Not Logical negation And Logical conjunction Or Logical disjunction XOr Logical exclusion Eqv Logical equivalence Imp Logical implication

Procedures: Subprograms and Functions


Procedures in VBScript, like those found in other popular programming languages, fall into two categories: subprograms and functions.

Procedure names adhere to the same rules as variable names. That is, they must begin with an alphabetic character, cannot contain embedded periods, and cannot exceed 255 characters in length. Procedures must be defined before they are referenced.

Note


Procedures in VBScript always pass variable parameters by value, not by reference.


Subprograms


Subprograms are declared using the Sub...End Sub statements. Immediately following the subprogram name are zero or more parameters, as shown in the following example:


...

Sub PrintStatus

     ...

End Sub

...

Sub NewResult( EnteredVal, Multiplier, ReturnedVal )

     'This subprogram multiplies EnteredVal by Multiplier, and

     'returns ReturnedVal.

     ReturnedVal = EnteredVal * Multiplier

End Sub

...

To call a subprogram, simply use the name of the subprogram in your code, such as:


...

NewResult A, B, C    'One way to call a subprogram

Call NewResult (A, B, C)  'Using the Call statement

...

Note in the preceding block of code that when the Call statement is used, parentheses around the parameter list are required.

Functions


Functions are declared using the Function..End Function statements. Functions differ from subprograms in that they return a variant value. The following block of code illustrates the declaration of a function:


...

Function CalcAmtDue( Trans() )

     Dim i, SubTotal, Tax

     TAX = 0.4

     For i = 1 to Ubound( Trans )

          SubTotal = Subtotal + Trans

     Next

     CalcAmtDue = SubTotal + (SubTotal * TAX)   'Required:  Set value of our 

                                                'function name before leaving.

End Function

...

Note that the most critical statement in the preceding block of code is the assignment of the function name, CalcAmtDue, to a value before termination of the function.

To use a function in VBScript, simply use the function name as an expression in any statement, such as:


NewAmount = CalcAmtDue( Trans() )

or:


If CalcAmtDue( Trans() ) > 500 Then Print "Present Credit Application"
Tip


To exit a function prematurely, before the End Function is encountered, use the Exit Function statement. Similarly, to terminate a subprogram before the End Sub, use the Exit Sub statement.


Conditional Execution


Like other languages, VBScript includes all of the conditional execution statements that are required in a structured development environment.

If...Then...Else

The first conditional execution statement that this section briefly discusses is If...Then...Else. The general syntax for this statement follows:


If expr Then

     ... Execute if expr is True

[Else

     ... Execute if expr is False (optional)]

End if

The following block of code illustrates some real-world If...Then...Else statements:


...

If AmtDue > CreditLine Then

     If (CreditHistory = GOOD_CREDIT) AND (CurrentEmployment = GOOD_EMP) Then

          CreditLine = CreditLine + AmtDue

     Else

          CompleteTrans = False

     End if

Else

     CompleteTrans = True

End if

...

Select Case

A second conditional execution statement, useful in many situations when If...Then...Else blocks would prove to be cumbersome and difficult to read, is the Select Case statement, similar to the switch statement in C. A brief grammar for this statement follows:


Select Case expr

     Case expr1

          ... Execute this code if expr = expr1

     [Case expr2

          ... Execute this code if expr = expr2]

     [Case exprn

          ... Execute this code if expr = exprn]

     [Case Else

          ... Execute this code if above Cases do not

          ... evaluate to True]

End Select

A real-world example of a Select Case statement in action follows:


...

Select Case ActionFlag

     Case 0

          MsgBox "Delete."

     Case 1

          MsgBox "Add."

     Case 2

          MsgBox "Edit."

     Case Else

          'If it is not <= TriggerPrice, then it is > TriggerPrice

          MsgBox "Invalid action specified."

End Select

...

Program Flow Control


VBScript provides three essential looping mechanisms, two of which will be discussed in this section:

A third conditional looping statement available in VBScript, While...Wend, will not be discussed in this section, because Do...Loop provides all of the capabilities of the While...Wend statement, and more.

For...Next

To repeat a body of statements a fixed number of times, use the For...Next statement. The general syntax for this statement is:


For var = beginval To endval [Step stepval]

    ... Insert statements to be repeated here

Next

The following code snippet illustrates nested For...Next statements initializing the values of a two-dimensional array:


...

For i = 0 to 9

     For j = 0 to 19

          Array(i, j) = i * j

     Next

Next

...
Tip


To exit out of a For...Next statement prematurely, execute the Exit For statement.


Do...Loop

The Do...Loop statement allows a block of VBScript to be executed until a stated condition evaluates to True. The conditional evaluation may occur before the VBScript block is executed in a pretest loop, or after it is executed at least once in the form of a post-test loop.

The pretest form of Do...Loop follows. Note that in this form it is possible that the script sandwiched between the Do and Loop statements may never be executed, depending on the evaluation of the initial expression:


...

Do [{While|Until} expr]

    ... VBScript block to execute while expr is True

Loop

...

An example of this form of a Do...Loop is shown in this VBScript example:


...

NewVal = 0

Do Until NewVal > 100

      NewVal = NewVal + CSng( InputBox ("Enter a new value to add.") )

Loop

MsgBox "The value is: " + CStr( NewVal )

...

The post-test form of the Do...Loop statement, which allows VBScript within the structure to be executed at least once, is shown following:


...

Do

    ... VBScript block to execute while expr is True

Loop [{While|Until} expr]

...

Here is an example in VBScript of a post-test Do...Loop statement:


...

NewVal = 0

Do

      NewVal = NewVal + CSng( InputBox ("Enter a new value to add.") )

Loop Until NewVal > 100

MsgBox "The value is: " + CStr( NewVal )

...
Note


It is possible in VBScript to create an endless loop using the Do...Loop statement. Before distributing your VBScript-enabled Web pages to the world, test your code carefully to ensure that you won't lock up the browsers of surfers in other countries, potentially causing an international incident.


Basic Input/Output


VBScript provides two extremely useful mechanisms for both displaying dialog boxes and requesting input from the user. These built-in functions are described in this chapter.

Displaying Simple Messages with MsgBox

The MsgBox() function allows a standard dialog box to be displayed. If required, the button clicked to close the dialog box may be determined. The syntax for MsgBox is


MsgBox(prompt[,buttons][,title][,helpfile,context_id])

In this syntax, the parameters are

Table 8.6 lists the options that are summed to produce the buttons parameter, defining the general characteristics of the MsgBox() function.

Table 8.6. Add values of desired attributes for buttons parameter.

Value Result Button Selection—Default: Ok 0 Ok button is displayed. 1 Ok and Cancel buttons are displayed. 2 Abort, Retry, and Cancel buttons are displayed. 3 Yes, No, and Cancel buttons are displayed. 4 Yes and No buttons are displayed. 5 Retry and Cancel buttons are displayed. Default Button Selection—Default: First 0 Assume the first button to be the default button. 256 Assume the second button to be the default button. 512 Assume the third button to be the default button. 768 Assume the fourth button to be the default button. Dialog Box Icon—Default: None 16 Use the Critical Message icon. 32 Use the Warning Query icon. 48 Use the Warning Message icon. 64 Use the Information Message icon. Modality—Default: Application Modal 0 Create an Application Modal dialog box. 4096 Create a System Modal dialog box; suspend all applications until the dialog box is closed.

If you are required to determine the button pressed by the user, the returned value from MsgBox() is provided. To determine the button selected, use Table 8.7.

Table 8.7. Return result of MsgBox().

Value: Selected Button: 1 Ok 2 Cancel (or ESCape) 3 Abort 4 Retry 5 Ignore 6 Yes 7 No

The following section of VBScript illustrates some examples of MsgBox() in use:


...

'In this example, we'll present a dialog box without

'concerning ourselves with overriding the default

'characteristics of the MsgBox.

MsgBox("This is a simple dialog box.")

'Now we'll display a message box that contains

'both Yes and No buttons (4), and a Query icon (32).

'We will also utilize the returned value.

ret = MsgBox("Do you wish to continue?", 4+32)

If ret = 7 Then

     'No

     Exit Sub

End If

...

Figure 8.1 shows an example of a simple MsgBox().

Figure 8.1. Simple MsgBox() example that uses Yes/No Buttons and a Query icon.

Requesting Simple Input with InputBox

The InputBox() function, like MsgBox(), is also a built-in routine that makes simple user interaction possible. Whereas MsgBox() is used for simple button selection and user notification, InputBox() allows a text entry to be made by the user. The syntax for InputBox() is shown following:


InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile, context_id])

In this syntax, the parameters are:

The return value of InputBox() represents the value typed in by the user, or an empty string ("") if Cancel was selected.

Here is an example of the InputBox() function being used in VBScript:


...

response = InputBox("Enter first and last name.", "Name Entry")

If response = "" Then

     'Cancel was pressed

     MsgBox ("Hey, you pressed Cancel!!")

End If

...

This example code produces the dialog box shown in Figure 8.2.

Figure 8.2. Simple InputBox() example.

Important Built-In Functions


Several important functions built into VBScript that allow for string manipulation and date/time manipulation have not been discussed in this chapter. Table 8.8 lists the most important string manipulation functions that will more than likely be used in any VBScript code that you develop. Instead of providing the syntax for each function, an actual example of how the function is used is shown.

Table 8.8. String manipulation functions.

Example Returns Explanation InStr("To All", "All") 4 Used to find the character position of the first occurrence of the second string in the first string. Left("To Whom It", 2) "To" Returns the specified number of characters from the given string, starting with the leftmost character. Right("To Whom It", 2) "It" Returns the specified number of characters from the given string, starting with the rightmost character. Len("Jordan") 6 Returns the length of the given string. LTrim(" Some ") "Some " Strips all leading spaces from the given string. RTrim(" Some ") " Some" Strips all trailing spaces from the given string. UCase("Kerrie") "KERRIE" Capitalizes all characters in the given string. Mid("Some Junk", 3, 2) "me" In this example, returns two characters starting with the third character.

Comparing VBScript to Visual Basic


For those developers already familiar with Visual Basic or Visual Basic for Applications (VBA), the use of VBScript will prove to be extremely straightforward. VBScript is simply a subset of Visual Basic; its primary design goal was to provide a "light" interpreted language that provides all of the fundamental features, but none of the icing, of Visual Basic.

Some of the most significant differences between the two languages are described following:

Tip


For more information on the differences between the two languages, see http://www.microsoft.com/vbscript/us/vbslang/vsgrpNonFeatures.htm.

In addition to language differences, the development environment (IDE) of VBScript is a throwback to the days of using an ASCII editor to create and debug your code. The development process, when using VBScript in an HTML document, usually consists of these steps:

  1. 1. Use an ASCII editor to modify an HTML document.
  2. 2. Fire up your Web browser and load the HTML document.
  3. 3. If you find any problem, in the form of either syntax errors or logical errors return to Step #1.

Tools such as the Microsoft ActiveX Control Pad make this process much simpler, especially when integrating ActiveX controls into your HTML document. However, even with this tool, for those who are accustomed to syntax highlighting, automatic syntax checking, and an integrated debugger with stepping, breakpoints, and watch variable facilities will be dissatisfied with the current VBScript development environment options.

VBScript and HTML: On the Rocks


Thus far this chapter's discussion has been based on VBScript itself, with little mention of the use of VBScript in an HTML document. The remainder of this chapter emphasizes how VBScript is utilized in HTML.

How to Embed VBScript into HTML


VBScript is included in HTML using the <SCRIPT></SCRIPT> tag. The following example illustrates a skeleton block used to embed VBScript in HTML:


...

<BODY>

<SCRIPT LANGUAGE = "VBScript">

<!--

     'Insert your VBScript statements here

     'This will include variable declarations, procedures and directives

-->

</SCRIPT>

</BODY>

...

Please note the following points:

It is recommended that all script be included in one contiguous <SCRIPT></SCRIPT> block embedded in either the <HEAD></HEAD> section or the end of the <BODY></BODY> section of a given HTML document. Although VBScript will not be affected by its placement, it is best, for readability and maintenance purposes, to group all script together in one consistent location.

VBScript Scoping Rules in HTML


There are two levels of scope defined in VBScript that affect the visibility and lifetime of variables: script and procedure.

The script level of scope involves all VBScript statements that are not included in any procedures (functions or subprograms), but that are included in the current HTML document, in any <SCRIPT></SCRIPT> blocks. Any variables declared at the script level can be seen by any script included at the procedure level. Variables are eliminated from memory when the current script is terminated by loading a new HTML document.

The procedure level of scope includes all variables declared within a procedure. These variables are eliminated from memory when the procedure in which they are declared is terminated by either an Exit or End statement.

Tip


The use of these scopes implies that there is no way to retain the value of variables between several HTML documents. If you require this capability, use HTML Cookies.


When Is VBScript Executed?


It is important to remember that VBScript is interpreted "on the fly", as your browser that supports VBScript, such as Microsoft Internet Explorer 3.0, parses through an incoming HTML document. Therefore, include VBScript that is required to immediately modify the attributes of a document at load-time in your <HEAD></HEAD> section, outside of any procedures. Including this code in the <HEAD></HEAD> section is simply a common convention, not a necessity; it could be placed in the <BODY></BODY> sections, but this is not recommended.

Any declared procedures are interpreted and stored in the client's local address space, ready for later execution. Any code at the script level (not embedded in procedures) is executed as encountered while an HTML document is parsed.

As in most other modern-day development environments, all non-script level procedures are executed based on the event-driven model. That is, a procedure is "triggered" based on an action that the user or some other entity (the object model, for example) triggers.

The next section begins to explain how objects and their actions are tied to VBScript procedures.

VBScript and the Internet Explorer Object Model


The Internet Explorer (IE 3.0) Object Model allows VBScript to be used to programmatically control both the current HTML page and the Web browser itself. For example, VBScript and the IE Object Model can be used to:

This object model, along with the programmatic power of VBScript, brings a tremendous amount of flexibility to the client side of any HTML document.

Tip


A significant portion of development in VBScript and HTML will require interaction with the IE 3.0 object model. For more information on this technology, refer to Chapter 7, "Microsoft Internet Explorer 3.0 and Its Scripting Object Model."


Using VBScript with an HTML Button


Through the IE 3.0 Object Model, some HTML elements, such as buttons and forms, may trigger the execution of specified VBScript procedures. In this section, you begin to create a real-world HTML page that demonstrates the initiation of a VBScript procedure based on an event.

The first example will enable the user to toggle the caption on an HTML button to read either "On" or "Off". Please refer to Listing 8.1; a complete explanation follows.

Listing 8.1. A simple HTML page that utilizes VBScript.


<HTML>

<HEAD>

<H2>

This page uses an HTML-defined button in a form to trigger

a VBScript subprogram, Button_Click.

</H2>

<Form Name = "frmTest">

        <!--

        Define a button called "button" whose initial caption

        will read "Try Me", and will call the VBScript

        subroutine Button_Click when the onClick event is

        triggered.  Remember that we're still in HTML definition

        here!

        -->

        <Input Type="Button" Name="Button" Value="Try Me"

                onClick="Button_Click" Language="VBScript">

</Form>

<SCRIPT LANGUAGE="VBScript">

<!--

Dim Toggle      'This global variable will retain our current

                'toggle state

Sub Button_Click

        'Now change the caption of the button defined on

        'frmTest to indicate the current value.

        If Toggle = 0 then

                Document.frmTest.Button.Value = "On"

                Toggle = 1

        else

                Document.frmTest.Button.Value = "Off"

                Toggle = 0

        end if

End Sub

-->

</SCRIPT>

<TITLE>Test VBScript!</TITLE>

</HEAD>

</HTML>

This HTML page performs the following tasks:

This example illustrates, at a rudimentary level, how the IE 3.0 Object Model allows VBScript to be used as the event handler for an HTML-defined button.

The purpose of this section was to illustrate the use of VBScript in an HTML document without the use of ActiveX controls. However, as the thrust of this book revolves around ActiveX, this chapter will not elaborate on the use of VBScript to control standard HTML elements; this topic falls outside of the scope of this chapter. The next section continues the discussion of VBScript, where you will utilize ActiveX components in HTML.

Using ActiveX and VBScript in HTML


As stated previously, VBScript can be used to programmatically define how an object on an HTML document must react to a triggered event. In the previous section, you examined how VBScript might be integrated along with a standard HTML object, a button in your example, to control what occurs when the user clicks on a button.

In this section, you will utilize readily available ActiveX components into an HTML document and react to various component-related events using VBScript.

Adding an ActiveX Control: The Hard Way


To add an ActiveX control to an HTML document is only slightly similar to adding a standard HTML element, such as a button, to an HTML document.

ActiveX controls and their associated properties are embedded in an <OBJECT></OBJECT> tag. The specified ActiveX control will appear in the HTML document wherever this tag occurs. The following code snippet illustrates the definition of an ActiveX control, in this case an IE 3.0 Label, one of the controls that ship with Microsoft Internet Explorer 3.0:


<OBJECT ID="IeLabel1" WIDTH=265 HEIGHT=70

 CLASSID="CLSID:99B42120-6EC7-11CF-A6C7-00AA00A47DD2">

    <PARAM NAME="_ExtentX" VALUE="5609">

    <PARAM NAME="_ExtentY" VALUE="1482">

    <PARAM NAME="Caption" VALUE="This is a Caption!">

    <PARAM NAME="Angle" VALUE="10">

    <PARAM NAME="Alignment" VALUE="4">

    <PARAM NAME="Mode" VALUE="1">

    <PARAM NAME="FillStyle" VALUE="0">

    <PARAM NAME="FillStyle" VALUE="0">

    <PARAM NAME="ForeColor" VALUE="#000000">

    <PARAM NAME="BackColor" VALUE="#C0C0C0">

    <PARAM NAME="FontName" VALUE="Arial">

    <PARAM NAME="FontSize" VALUE="12">

    <PARAM NAME="FontItalic" VALUE="1">

    <PARAM NAME="FontBold" VALUE="1">

    <PARAM NAME="FontUnderline" VALUE="0">

    <PARAM NAME="FontStrikeout" VALUE="0">

    <PARAM NAME="TopPoints" VALUE="0">

    <PARAM NAME="BotPoints" VALUE="0">

</OBJECT>

From the preceding HTML, please note the following points:

The problems with adding ActiveX controls to HTML pages without the assistance of any other utility should be fairly clear to those with experience with a "point and click" development environment such as Visual Basic. These problems are summarized following:

One possible solution that applies even with add-on development tools might be to browse through Web-based documentation that describes properties and methods for each object. Microsoft's Web site contains excellent descriptions of each of the ActiveX controls bundled in IE 3.0. However, this still does not approach the ease of development found in environments such as Borland Delphi or Microsoft Visual Basic.

The solution to most, but not all, of these dilemmas is described in the next section.

Making Life Easier with Microsoft ActiveX Tools


A good friend of mine once said that, by nature, developers are lazy people. When a programmer finds a task difficult to accomplish, he (or she) will either seek a tool that someone else has developed to help get the job done more quickly or develop a tool themselves that shaves either milliseconds or days off a programming task.

This is a good thing. Microsoft, the makers of the ActiveX technologies that make programmers' lives so very interesting, have also released two invaluable tools that dramatically assist in the process of using ActiveX controls in HTML documents: The ActiveX Control Pad and the ActiveX Control Lister. Both of these tools can be found in the ActiveX SDK.

Tip


If you do not have access to this SDK, visit the Microsoft ActiveX SDK Web site at http://microsoft.com/intdev/sdk. Follow the links to the download area for more details.


ActiveX Control Lister

As mentioned earlier, any time an ActiveX control is added to a Web page using the <OBJECT> tag, the class ID is required. Normally the determination of this value would require the perusal of the Windows system registry.

The ActiveX Control Lister makes this process much simpler by presenting a dialog box, after scanning your system registry, that contains all of the ActiveX controls installed on your system. Additionally, you can right-click on any of the controls in this list box to bring up a pop-up window that will allow you to copy the essentials for the <OBJECT> tag, including the CLSID, into the Windows clipboard for easy pasting into a text HTML file. What a lifesaver!

Figure 8.3 represents a typical ActiveX Control Lister display, along with the pop-up window that appears when the right mouse button is clicked.

Figure 8.3. The ActiveX Control Lister in action.

When Copy is selected from the pop-up menu, the minimal <OBJECT> tag requirements for the selected control are pasted into the clipboard. For example, the following text was pasted into the clipboard when the Microsoft Forms 2.0 Image ActiveX control was selected:


<Object

     Id="Microsoft Forms 2.0 Image"

     Classid="clsid:4C599241-6926-101B-9992-00000B65C6F9"

     Width=80

     Height=30 >

</Object>

If you select Options from this pop-up menu, you can configure the contents and format of the information that is copied into the clipboard, such as character case, values for the initial width and height attributes, and whether or not the text should appear on one line or multiple lines.

This utility is a "must have" for any Web page developer who utilizes ActiveX controls.

ActiveX Control Pad

The ActiveX Control Pad is described in detail in Chapter 11, "Using ActiveX Control Pad," so this section doesn't go into any significant detail regarding this tool. However, you should understand the fundamental operation of this utility, especially as it applies to VBScript.

At first glance, it may appear as though the ActiveX Control Pad is simply a text editor, with perhaps the ability to automatically present a basic HTML framework in new HTML documents. However, it is much, much more than that. In essence, the ActiveX Control Pad provides the developer with an HTML "Integrated Development Environment" that is especially useful when integrating ActiveX controls, the Internet Explorer 3.0 Object Model, and VBScript or JavaScript.

Here is a brief list of the most important features found in this product:

Note


Another important attribute of this product, HTML Layouts, will not be discussed in this section, but is discussed in Chapter 11. HTML Layouts give the Web page designer much more control over how controls will be positioned on the screen.

Figure 8.4 illustrates a typical operation utilized in the ActiveX Control Pad: changing properties for an object, in this case a label, using the Control Editor.

Figure 8.4. The ActiveX Control Pad's Control Editor.

In some cases, a picture is definitely worth a thousand words. Compared to a straight text editor, the advantage of using the ActiveX Control Pad to modify your HTML documents should be apparent.

Of course, simply inserting ActiveX controls into your Web documents and manipulating their properties is only one quarter of the battle. The remaining three quarters revolve around controlling these controls, and allowing them to interact with each other through VBScript or JavaScript.

The ActiveX Control Pad, through the Script Wizard, gives you an easy way to:

Figure 8.5 illustrates an event handler being designed for the Click event of the lblWelcome object, an ActiveX label control. Note the other objects and events that are displayed in the upper left panel, and the possible actions listed in the upper right panel.

Figure 8.5. The Script Wizard in the ActiveX Control Pad.

Now that you have a rudimentary understanding of what you can accomplish with the ActiveX Control Pad, this chapter on VBScript will wrap up by designing an interactive Web page that utilizes ActiveX Controls with underlying logic created in VBScript.

An Interactive Page Using VBScript and ActiveX Controls


In this section, you create a Web page that utilizes several ActiveX controls, tying together those controls and controlling some elements of the IE 3.0 Object Model through VBScript. The interactive page that will be demonstrated here is a typical user entry screen that might appear when a Web surfer is requesting information on one or more products from a typical Web site.

For those who have developed interactive forms in standard HTML, you may ask why the example uses ActiveX labels, edit boxes and other controls over elements that are built into the HTML standard. This is for two reasons. First, the purpose of this book is to discuss ActiveX controls, not necessarily built-in HTML elements. Second, ActiveX controls give the developer much more flexibility with respect to their attributes than built-in HTML elements.

Note


The CD-ROM included with this book contains the HTML source for each phase of development included in this section, beginning with INTER.HTM, then following with INTER2.HTM, and INTER3.HTM.

Note


The goal of this section is to illustrate the use of VBScript fundamentals described in the first half of this chapter. Therefore, I will not discuss the use of the ActiveX Control Pad, which was used to generate these pages.


The Framework


The first phase in designing any HTML page is to lay out the basic components of the page. You'll use VBScript and the methods available in the IE 3.0 Object Model to create your basic framework, shown in Listing 8.2.

Listing 8.2. The "Basics"—Your Framework


<HTML>

<HEAD>

<TITLE>Sample Interactive Page</TITLE>

<SCRIPT LANGUAGE="VBSCRIPT">

<!--

'This script is executed immediately, when the form is loaded...

Dim TodayNum

'Change the background color to white

window.document.bgColor = "#FFFFFF"

'Print the name of the current day

TodayNum = Weekday( Date )

window.document.write("<H3>It is  "&NameOfDay(TodayNum)&" at "&Time&"</H3>")

'Create a new paragraph, and add it to the current document:

window.document.write("<P><H4>")

window.document.write("Thank you for requesting information on our products!")

window.document.write("Please carefully fill out each entry on this form.  ")

window.document.write("When you are finished, click on the Submit button.")

window.document.write("</H4></P>")

Function NameOfDay( DayNum )

     'Given a day number, return the full name of the

     'day; use with WeekDay built-in function.

     Select Case DayNum

     Case 1

          NameOfDay = "Sunday"

     Case 2

          NameOfDay = "Monday"

     Case 3

          NameOfDay = "Tuesday"

     Case 4

          NameOfDay = "Wednesday"

     Case 5

          NameOfDay = "Thursday"

     Case 6

          NameOfDay = "Friday"

     Case 7

          NameOfDay = "Saturday"

     End Select

End Function

-->

</SCRIPT>

</HEAD>

<BODY>

</BODY>

</HTML>

Note the following points about this basic framework:

The image shown in Figure 8.6 depicts your current Web page.

Figure 8.6. Your "base" Web page, without ActiveX Controls.

Adding ActiveX Controls


Now that you have a very primitive framework for your page, you can begin adding several ActiveX controls that will enable the user to enter all the information the program will need to process his request for information. You will also construct a simple HTML table, each cell of which will be used to contain an ActiveX control. Remember that without the use of a table, ActiveX objects will appear in order as they are encountered in your HTML document. Using tables is a simple way to ensure that the controls in your form are properly positioned.

Note


Most of the ActiveX controls used in this example are shipped with the ActiveX Control Pad, and they are not part of the standard Internet Explorer 3.0 control set. Information pertaining to the properties, methods, and events that apply to these controls can be found in the ActiveX Control Pad help system.

Tip


For many ActiveX controls, including the ones shipped with the ActiveX Control Pad, the CodeBase property should be defined, indicating a URL (a Web site, ftp site, or gopher site, for example) where the control can be downloaded. If a Web page is loaded that uses an ActiveX control that the user does not already have on her system, this mechanism will provide a means to retrieve and register the needed control automatically.

Listing 8.3, taken from the <BODY></BODY> portion of your HTML document, contains your basic table and all of the ActiveX controls that will be contained in the cells of the table.

Listing 8.3. Your <BODY> with a table and ActiveX Controls.


<BODY>

<TABLE BORDER=0>

<TR>

        <TD>

             First Name:

        </TD>

        <TD>

        <OBJECT ID="txtFirstName" WIDTH=291 HEIGHT=24

         CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002F3">

        <PARAM NAME="VariousPropertyBits" VALUE="746604571">

        <PARAM NAME="Size" VALUE="7694;635">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</TD>

</TR>

<TR>

        <TD>

            Last Name:

        </TD>

        <TD>

        <OBJECT ID="txtLastName" WIDTH=291 HEIGHT=24

        CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002F3">

        <PARAM NAME="VariousPropertyBits" VALUE="746604571">

        <PARAM NAME="Size" VALUE="7694;635">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</TD>

</TR>

<TR>

        <TD>

            Company:

        </TD>

        <TD>

        <OBJECT ID="txtCompany" WIDTH=291 HEIGHT=24

         CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002F3">

        <PARAM NAME="VariousPropertyBits" VALUE="746604571">

        <PARAM NAME="Size" VALUE="7694;635">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</TD>

</TR>

<TR>

        <TD>

             Mail Address:

        </TD>

        <TD>

        <OBJECT ID="txtEMail" WIDTH=291 HEIGHT=24

        CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002F3">

        <PARAM NAME="VariousPropertyBits" VALUE="746604571">

        <PARAM NAME="Size" VALUE="7694;635">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</TD>

</TR>

<TR>

        <TD>

            Product Interest:

        </TD>

        <TD>

        <OBJECT ID="lstProducts" WIDTH=203 HEIGHT=76

         CLASSID="CLSID:8BD21D20-EC42-11CE-9E0D-00AA006002F3">

        <PARAM NAME="ScrollBars" VALUE="3">

        <PARAM NAME="DisplayStyle" VALUE="2">

        <PARAM NAME="Size" VALUE="5362;2011">

        <PARAM NAME="ListStyle" VALUE="1">

        <PARAM NAME="MultiSelect" VALUE="1">

        <PARAM NAME="SpecialEffect" VALUE="0">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</TD>

</TR>

        <TD>

             Level of Interest:

        </TD>

        <TD>

        <OBJECT ID="cmbInterest" WIDTH=203 HEIGHT=24

        CLASSID="CLSID:8BD21D30-EC42-11CE-9E0D-00AA006002F3">

        <PARAM NAME="DisplayStyle" VALUE="7">

        <PARAM NAME="Size" VALUE="5366;635">

        <PARAM NAME="ListRows" VALUE="3">

        <PARAM NAME="MatchEntry" VALUE="1">

        <PARAM NAME="ShowDropButtonWhen" VALUE="2">

        <PARAM NAME="FontCharSet" VALUE="0">

        <PARAM NAME="FontPitchAndFamily" VALUE="2">

        <PARAM NAME="FontWeight" VALUE="0">

    </OBJECT>

</TD>

</TR>

</TABLE>

<PLAINTEXT>

</PLAINTEXT>

<CENTER>

<OBJECT ID="cmdSubmit" WIDTH=159 HEIGHT=49

 CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57">

    <PARAM NAME="Caption" VALUE="Submit Information">

    <PARAM NAME="Size" VALUE="4202;1291">

    <PARAM NAME="FontEffects" VALUE="1073741825">

    <PARAM NAME="FontHeight" VALUE="200">

    <PARAM NAME="FontCharSet" VALUE="0">

    <PARAM NAME="FontPitchAndFamily" VALUE="2">

    <PARAM NAME="ParagraphAlign" VALUE="3">

    <PARAM NAME="FontWeight" VALUE="700">

</OBJECT>

</CENTER>

</BODY>
Tip


If you're wondering where the author got the PARAM NAME values, remember that this page was designed using the ActiveX Control Pad, which gives the developer all available parameters for each ActiveX control.

With respect to the preceding listing, note the following points:

In Figure 8.7, you can see what your current Web page looks like when viewed through the eyes of a Web browser.

Figure 8.7. Your Web page with several ActiveX Controls.

Controlling Your Controls with VBScript


Now that you've created your primary controls, you need to place VBScript behind them to:

Your first task is to populate both the product list and level of interest list when the Web page is loaded. To do this, you will use the OnLoad event of the Window object, which is part of the IE 3.0 object model. The AddItem method for the two controls allows you to add items to the list box and combo box. The following subprogram should be placed at the end of your existing <SCRIPT> block:


Sub Window_onLoad()

     'Load up our list box with default values

     lstProducts.AddItem "Wacky Widgets"

     lstProducts.AddItem "The Roto Box"

     lstProducts.AddItem "Gucci Babies"

     'Load up our combo box with default values

     cmbInterest.AddItem "Purchase w/in a Week"

     cmbInterest.AddItem "Purchase w/in a Month"

     cmbInterest.AddItem "Just Browsing"

end sub

The next task, acting upon a Tab key, is fairly simple and does not require the use of VBScript. All that is required is a modification of one of the default parameters for each of the controls that you've added. The following parameter should be added to each text box control; the other controls already include this behavior by default:


<PARAM NAME="TabKeyBehavior" VALUE="-1">

Your final task, input validation, does, of course, require the inclusion of additional VBScript. You will simply check the value of each of your controls in the Click event of your Submit button (cmdSubmit), ensuring that information has been entered into each field.

The subroutine shown in Listing 8.4 should be added to the end of the existing <SCRIPT> block.

Listing 8.4. Your input validation routines.


Sub cmdSubmit_Click()

     Dim i, OneSel, FinalMsg, resp

     'All input validation is done here.

     if Trim(txtFirstName.Value) = "" then

          MsgBox "You must enter your First Name!",48, "Input Error" 'Warning

          exit sub

     end if

     if Trim(txtLastName.Value) = "" then

          MsgBox "You must enter your Last Name!", 48, "Input Error"   'Warning

          exit sub

     end if

     if Trim(txtCompany.Value) = "" then

          MsgBox "You must enter your Company Name!", 48, "Input Error"'Warning

          exit sub

     end if

     if Trim(txtEMail.Value) = "" then

          MsgBox "You must enter your Email Address!",48, "Input Error"'Warning

          exit sub

     end if

     OneSel = False

     For i = 0 to (lstProducts.ListCount - 1)

          If lstProducts.Selected = True then

               OneSel = True

               Exit For

          End If

     Next

     If OneSel = False Then

          MsgBox "You must select one or more Products!",48 ,"Input Error"

          Exit Sub

     End If

     If Trim(cmbInterest) = "" then

          MsgBox "You must select your Level of Interest!", 48, "Input Error"

          exit sub

     End If

     'If we've made it here, all entries are O.K., so summarize

     'and ask the user if they want to continue...

     'Note Chr(13) moves to the next line in a dialog box...

     FinalMsg = "Please confirm your entries..."+Chr(13)+Chr(13)

     FinalMsg = FinalMsg + "Name: " + txtFirstName + " " + txtLastName + Chr(13)

     FinalMsg = FinalMsg + "Company: "+ txtCompany + Chr(13)

     FinalMsg = FinalMsg + "EMail Address: "+ txtEmail + Chr(13) +  Chr(13)

     FinalMsg = FinalMsg + "Product Interest: " + Chr(13)+Chr(13)

     For i = 0 to (lstProducts.ListCount - 1)

          If lstProducts.Selected = True then

               FinalMsg = FinalMsg + "      " + lstProducts.List + Chr(13)

          End If

     Next

     FinalMsg = FinalMsg + Chr(13) + "Are these correct?"

     resp = MsgBox (FinalMsg, 4+32, "Confirm Entries...")

     If resp = 6 Then 'Yes

          'Submit material - do whatever processing is required in your

          'application to send this information to the server....

          '...

          'Assuming everything was O.K., send user confirmation

          TodayNum = Weekday( Date )

          document.clear

          document.write

          document.write("<P><H4>")

          document.write("Your submission has been received." )

          document.write("<I>Thank you for your interest in our products!</I>" )

          document.write("" )

          document.write("</H4></P>")

          TodayNum = TodayNum + 1

          if TodayNum = 8 then TodayNum = 1

          document.write("<H3>Your response should be received by: 5:00 PM

               on " & NameOfDay(TodayNum)& "!</H3>")

          document.close

     Else

             MsgBox "You may now modify your entries as necessary.  When you are

[icc]   ready to re-submit, press the Submit button.", 0, "Correct Your Entries"

     End if

End sub

With respect to the preceding listing, note the following points:

This concludes the development of your basic interactive Web page. To complete this page, you might add appropriate code for your particular system to properly submit information to a server, either through CGI or some other server API mechanism.

Summary


VBScript is a fairly limited but functional scripting language that is appropriate for use as a low-overhead Internet scripting tool. As the world of the Internet changes on a minute-to-minute basis, one of the best sources of information will be on the Internet itself, where companies like Microsoft and Netscape share new development strategies and distribute their scripting product directions and documentation. When developing an HTML page using ActiveX controls, you will more than likely find yourself jumping back and forth between your HTML development environment, such as the ActiveX Control Pad, and your Internet browser of choice, allowing you to retrieve the latest technical documentation available on the Web at design time.

The following list summarizes the most important issues discussed in this chapter:

SAMS Publishing

ActiveX Programming Unleashed, 154-8, 8

filename: axu8MB.DOC

MS Pages: 26
Listing Pages: 12
Figure Count: 7
------------ -----
Total Pages: 41

Last Update: 10/02/96 11:02 AM

Previous Page Page Top TOC Next Page