Chapter 13

VBScript and OLE Controls


CONTENTS

If you have been programming for any length of time, you have probably run across the programming language called Visual Basic. Visual Basic is a compiled language that is relatively simple to learn and comes with a lot of pre-built code to enable programmers to reuse code. Furthermore, Microsoft intends to incorporate a subset of its Visual Basic syntax into its new Web browser, Microsoft Internet Explorer. Visual Basic Script represents the competing scripting language to JavaScript. Microsoft has changed its overall strategy to incorporate the Internet in a big way-which means it is moving to compete directly with Netscape for browser market share.

Visual Basic Script (or VBScript, as it is often called) enables Web content creators to script, automate, and customize their Web pages in a similar fashion to JavaScript. VBScript takes scripts embedded in HTML pages and sends them to a compiler on the client side, which then compiles and runs the script-much like a regular Visual Basic Program. You can validate form submissions, generate HTML on-the-fly, or even create a client-side game that is compiled on-the-fly. You might even include special information that the user provided just moments before.

Visual Basic Script is a subset of the total Visual Basic language. Many of the potentially hazardous features of Visual Basic have been eliminated from VBScript to disallow such constructs as VB viruses or Trojan horses being loaded along with the interactive content on the Web page. Visual Basic script is at the bottom of a three-tiered level of complexity of packages that use Visual Basic.

Language Overview

If you have learned to some extent the syntax of JavaScript, it will go a long way toward helping you learn about Visual Basic Script, and knowing something about Visual Basic will help you even more. Many of the features you find in JavaScript have their mirrors in Visual Basic script, which is primarily due to the fact that there is a basic set of features all scripting languages should have in order to handle conditional execution of code, or handling text input and output, etc. What you will find as you begin to learn about Visual Basic script is that you have a powerful new set of tools that have in the past been applied to programming applications, which are now being applied to the web.

Each of the sections below talks about a different aspect of Visual Basic Script, and to some extent builds on the knowlege gained from the previous section. My best recommendation to you as a scripter is to download the SDK for the Microsoft ActiveXª enviroment (which includes the pre-release version of Microsoft Internet Explorer) at http://www.microsoft.com/intdev/sdk/. From there, you should visit Microsoft's Visual Basic web site (at http://www.microsoft.com/vbscript/vbsmain.htm). Once you get familiar with the language from here and the web site, you should be well on your way to creating interactive web sites (literally Internet-based applications) with Visual Basic Script.

Table 13.1 gives you an overview of the syntax of the language.

Table 13.1   Visual Basic Script Syntax

Category of ElementSyntax Used
ArraysDeclaration (Dim, Static, etc.)
LBound, UBound
ReDim, Erase
Assignment=
Let
Set
CommentsUsing REM and '
Control flowDo...Loop For
...Next, For Each...Next
While...Wend
If...Then...Else
Error trapping On Error Resume Next
Err object
LiteralsEmpty
Nothing
Null
True, False
User-defined literals:
     123.456; "Foo", etc.
MiscellaneousLine continuation character ( _ )
Line separation character ( : )
Nonconforming Identifiers o.[My long method name]
OperatorsArithmetic:
    +, -, *, /, \, ^, Mod
    Negation (-)
    String concatenation (&)

Comparison:
    =, < >,, <,, >,, < =, > =, Is

Logical:
    Not
    And, Or, Xor
    Eqv, Imp

OptionsOption Explicit
ProceduresDeclaring procedures:
Function
     Sub
Calling Procedures:
    Call
Exiting procedures:
    Exit Function
    Exit Sub
Parameters for procedures:
    ByVal, ByRef
VariablesProcedure-level:
    Dim
    Static

Module-level:
    Private, Dim

Data Types

Visual basic uses only one data type: variant. It needs only this one type because VBScript takes the data within some variable and treats it as a number when appropriate and treats it as a text string if that is the logical intended type. VBScript uses the context in which a variable is called to determine how a variable is "typed." VBScript enables you to use subtypes, which can further define how the variant type is interpreted. Table 13.2 lists the various subtypes that VBScript understands.

Table 13.2  Listing of Subtypes to the Data Type variant

SubtypeExplanation
EmptyVariant is not initialized. Value is either zero for numeric variables or a zero-length string ("") for string variables.
NullVariant intentionally contains no valid data.
BooleanContains either True or False.
ByteContains integer in the range zero to 255.
IntegerContains integer in the range -32,768 to 32,767.
LongContains integer in the range -2,147,483,648 to 2,147,483,647.
SingleContains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
DoubleContains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Date (Time)Contains a number that represents a date between January 1, 100 to December 31, 9999.
StringContains a variable-length string that can be up to about 2 billion characters in length.
ObjectContains an OLE Automation object.
ErrorContains an error number.

Variables

VBScript enables you to create and use many kinds of variables-which are similar to JavaScript variables in that they are locations where values of a given kind are held.

To define a variable in VBScript, you use the DIM command. This is the mirror image of the VAR command in JavaScript and is used similarly:

<SCRIPT LANGUAGE="VBS">
              <!--
               Dim MyVariable
              -->
              </SCRIPT>

VBScript variables follow the same kinds of conventions as JavaScript variables; for example, they must begin with an alphanumeric character, are limited to 255 characters, and must be unique to the scope in which they are called. Unlike JavaScript, where variables are limited by the scope in which they are called, you can declare static variables in VBScript, which enables them to persist after the function calling them has finished. Listing 13.1 is an example.


Listing 13.1  Creating a Static Variable (Accumulator)  

<SCRIPT LANGUAGE="VBS">
              <!--
               Function ClockTime(anumber)
                  Static Accumulator
                  Accumulator = Accumulator + anumber
                  ClockTime = Accumulator     
               End Function
              -->
              </SCRIPT>

In this case, you would be able to execute the function ClockTime over and over and be able to rely on the fact that the variable Accumulator continued to persist between calls. In this way, Accumulator would be able to consistently increase based on the variable anumber that you pass to it each time.

NOTE
Note that when you set a variable to be Static it will persist between function calls, yet is still only avaliable to that function because its scope is limited to the function.

Arrays  Arrays in VBScript are created in a way somewhat different from JavaScript. In VBScript, you create an array by using the DIM statement and setting an upper limit for the size of the array, for example, Dim Foo(30). This would create an array of 31 items, starting with Foo(0) and ending with Foo(30). If you want to assign a value to any of the items in this array, simply use the equal sign (=), as follows:

Foo(10) = 100
Foo(11) = 99

Contrast this to JavaScript, in which you first create an array constructor, as in listing 13.2.


Listing 13.2   Creating an Array in JavaScript

function MakeMyArray(x){
this.length=x;
for (var i=1; i<= ; i++) {
this[i]=0}
return this
}
}

Then you use new to create an instance of that array, as in

var thisValue = new MakeMyArray(500);

In VBScript, you can create arrays of up to 60 dimensions. For example, if you want to create a 3-dimensional array with 100 elements in the first dimension, 50 in the second, and 10 in the third, you could call the array as shown in listing 13.3.


Listing 13.3   Creating a 3D array in VBScript

<SCRIPT LANGUAGE="VBS">
<!-- A 3D array
	Dim theArray(99, 49, 9)
-->
</SCRIPT> 

NOTE
Note that when you create an array in VBScript, you are sending not the size of the dimension, but the name of the highest value in that dimension, which is one less than the size of the dimension. So an array of size 10 is created with an index of 9.

This next feature seems unique to VBScript, although JavaScript may have this functionality as well: you can create an array whose size can change dynamically over time. This is called (appropriately) a Dynamic array and is created the same way you would create a regular array only you do not place a value in the parentheses when you first create it. You must use ReDim with a value to set the correct size for that time. Every time you want to resize that array, you use ReDim again with the correct index values.

NOTE
If you ReDim an array to a smaller size you will lose the data in the upper levels of your data.

VBScript Constants

Although JavaScript does have a few constants in its Math() method, VBScript uses many more for various programming functions. Many of the functions in VBScript have their own built-in constants-which cannot assume different values. Table 13.3 lists a few of the more common ones.

Table 13.3  Commonly Used Constants

Constant
Description
vbCrCarriage return character
vbCrLfCarriage return and line feed characters
vbFalseBoolean value represented by 0
vbLfLine feed character
vbTrueBoolean value represented by -1

VBScript Operators

VBScript operators work in much the same way as those in JavaScript, and they follow the same order of precedence as most fifth generation languages, such as Java, C++, and Perl. Table 13.4 shows the arithmetic, comparison, and logical operators in order of precedence.

Table 13.4  Visual Basic Script Operators

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

Control Flow in VBScript

Most languages need some form of control of program flow, such as IF…THEN…ELSE statements, loops, and so on. VBScript provides its own syntax, which is similar in some ways to JavaScript, but does not use parentheses. This is due to VBScript's roots in BASIC, as opposed to JavaScript's roots in C++, which groups items together using parentheses. Listings 13.4 and 13.5 are some examples of using control statements in Visual Basic Script.


Listing 13.4  IF…THEN…ELSE Example

<SCRIPT LANGUAGE="VBS">
              <!--
               Sub ShowtUser(value)
                   If value = 0 Then
                       Musicplay.Jazz = True
			Videoplay.Batman = Slow
                   Else
                       Musicplay.Jazz = False
			Videoplay.Batman = Fast
                   End If
               End Sub
              -->
              </SCRIPT>


Listing 13.5  DO…WHILE Loop Example

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

When you use DO...WHILE you can perform some action repeatedly until some condition is met. You can use UNTIL to perform a loop until the condtion is true. If you want to check another condition and exit the loop early, you can use the EXIT DO command with an IF...THEN condition within the loop. If you wish to perform some function on a series of objects, you can use FOR EACH...NEXT, as seen in listing 13.6.


Listing 13.6  Using For Each…Next in VBScript

<SCRIPT LANGUAGE="VBS">
              <!--
Sub
For Each myState in myCountry
If myState.Governer = "Democrat" Then 
myState.Color="green"
End If
Next
End Sub
              -->
      </SCRIPT>

Visual Basic Script Procedures

VBScript uses two different kinds of procedures, as opposed to JavaScript's one function statement. In VBScript, you have the SUB procedure and the FUNCTION procedure. With the SUB procedure, you can send it values and it can perform actions, but it does not return a value. The FUNCTION procedure is identical, except that it returns a value. Listings 13.7 and 13.8 are examples of the SUB and FUNCTION procedures.


Listing 13.7  Using Sub

<SCRIPT LANGUAGE="VBS">
              <!--
               Sub ConvertTime()
                  time = InputBox("Please enter the time in seconds.",1)
                  MsgBox "The time is " & Seconds(time) & " O'clock
               End Sub
              -->
              </SCRIPT>


Listing 13.8  Using Function

<SCRIPT LANGUAGE="VBS">
              <!--
 Sub ConvertTime()
                  time = InputBox("Please enter the time in seconds.",1)
                  MsgBox "The number of hours is " & Seconds(time) & "
                                        O'clock
               End Sub
               Function Seconds(theTime)
                   Seconds=theTime / 120
               End Function
              -->
              </SCRIPT>

Syntax Summary

Although VBScript is easy to learn, there are a large number of keywords to learn for the various functions, methods, operators, etc. Tables 13.5 through 13.9 are tables that supply you with these keywords grouped by type as a reference.

Table 13.5  Functions in VBScript

Functions
Abs Array Asc
Atn CCBool
CByte CDate CDbl
Chr CInt CLng
Cos CreateObject CSng
CStr CVErr D
Date DateSerial DateValue
Day EExp
HHex Hour
IInputBox InStr
Int, Fix sIsArray IsDate
IsEmpty IsError IsNull
IsNumeric IsObject
LBound LCase Left
Len Log LTrim, RTrim, and Trim
Mid Minute Month
MsgBox Now Oct
Right Rnd Second
Sgn Sin Sqr
Str StrComp String
Tan Time TimeSerial
TimeValue UBound UCase
Val VarType Weekday
Year   

Table 13.6  VBScript Methods

Methods
RaiseClear

Table 13.7  VBScript Operators

Operators
+ And &
/ Eqv ^
Imp \ Is
Mod * Not
Or - Xor

Table 13.8    VBScript Statements

Statements
Call Dim Do...Loop
Erase Exit For...Next
For Each...Next Function If...Then...Else
Let LSet Mid
On Error Private Public
Randomize ReDim Rem
RSet Select Case Set
Static Sub While...Wend

Table 13.9    VBScript Objects and Properties

ObjectsProperties
ErrDescription
 HelpContext
 HelpFile
 Number
 Source

Visual Basic Script in HTML

As you have seen in many of the previous listings, Visual Basic Script uses the same SCRIPT.../SCRIPT tags that JavaScript does. Listing 13.9 is an example of a simple VBScript.


Listing 13.9  Simple Script

<SCRIPT LANGUAGE="VBS"> 
              <!--
                 Function CanDeliver(Dt)
                    CanDeliver = (CDate(Dt) - Now()) > 2
                 End Function
              -->
              </SCRIPT>

Notice that this follows much of the same rules as JavaScript-especially to the extent that you must use comments to keep older browsers from viewing the code inline. Listing 13.10 is an example of a VBScript that opens a dialog box in the browser when the user clicks a FORM button.


Listing 13.10  "Hello There" in VBScript

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

VBScript expands on the <SCRIPT> format and allows you to add additional
attributes to this tag. Suppose you had a button in a form such as

<form>
<input type="button" name="screamer" Value="yell" >
</form>

You could create a script that opens a window with a message "HELLO THERE!" like this:

<SCRIPT LANGUAGE="VBS" EVENT="OnClick" FOR="Button1">
<!-- the message
	MsgBox "HELLO THERE!"
-->
</SCRIPT>

The EVENT attribute tells VBScript which event handler to monitor for this script, and the FOR attribute indicates which element (in this case a form input button) to monitor the event handler.

Visual Basic Script and OLE Automation

Visual Basic Script also enables programmers to set properties and methods of OLE controls as well as applets created with Java. Listing 13.11 gives an example of an OLE controller using a proposed INSERT tag.


Listing 13.11  An Example OLE Control Using the INSERT Tag

         <Insert>
          clsid = {"000effe0000005045454504342"}
          OLEcontrol.forecolor = true
          OLEcontrol.animate
          javaapplet.forecolor = olecontrol.forecolor
       <\Insert>

OLE controls, now known as ActiveXª controls, consist of binary software objects that are highly reusable. They contain well-defined properties and I/O interfaces. The advantage of using OLE controls is that you can quickly create sophisticated applications by pulling together simpler objects through a language such as Visual Basic, although you could develop them in other languages such as Perl, or C++. OLE controls could consist of animated graphics, floating toolbars, dynamically built forms, and more. You can get and set properties of OLE controls and invoke its methods just as if this were a form element that you might check or set (see the following section, "VBScript and Forms" ). Let's suppose you had a (fictional) OLE control embedded in an HTML document using <OBJECT> that displayed a spinning earth-as in listing 13.12.


Listing 13.12  The World OLE Control

<OBJECT
CLASSID="clsid:{5t5636y3i-6e45w-23r37}"
id=theWorld
width=300
height=200
align=top
hspace=2
vspace=0
>
<PARAM NAME="Name" VALUE="Earth">
<PARAM NAME="Size" VALUE="large">
<PARAM NAME="Color" VALUE="blue-green">
</OBJECT>

A form to change the color might be:

<FORM NAME="WorldChange">
<INPUT TYPE="TEXT" NAME="newColorValue" SIZE=10>
<INPUT TYPE="BUTTON" NAME="cmdChangeColor" VALUE="Change Color">
</FORM>

And the VBScript that might change the object's value might look like that shown in listing 13.13.


Listing 13.13  VBScript for the World Color Control

<SCRIPT LANGUAGE="VBS">
<!--
Sub cmdChangeColor_onClick
	theWorld.Color = Document.WorldChange.newColorValue.Value
End Sub
-->
</SCRIPT>

This is one area that VBScript has leaped ahead of JavaScript, at least as of this writing. The fact that VBScript can modify attributes and methods of OLE controls would be equivalent to JavaScript being able to do the same with plug-ins and Java. Until this happens, VBScript has a clear advantage for creating Internet-based applications using OLE controls instead of Java applets.

VBScript and Forms

VBScript can perform the same kinds of form input validation as JavaScript. Although it uses syntax specific to VBScript, it has many similarities to JavaScript, such as the OnClick event handler. Listing 13.14 is an example of a form with a simple validation function.


Listing 13.14    A Simple Form Validation Example

              <HTML>
              <HEAD><TITLE>Simple Validation</TITLE>
              <SCRIPT LANGUAGE="VBS"> 
              <!--
              Sub Submit_OnClick
                      If IsNumeric(Document.myForm.Foo1.Value) Then
                              If Document.myForm.Foo1.Value < 100 Or
                                   Document.myForm.Foo1.Value > 1000 
                                      MsgBox "Please enter a number
                                       between 100 and 1000."
                              Else
                                      MsgBox "Your Number Has Been
                                       Accepted"
                              End If
                      Else
                              MsgBox "Please enter a numeric value."
                      End If
              End Sub
              -->
              </SCRIPT></HEAD>
              <BODY>
              <FORM name="myForm">
              Enter a value between 10 and 1000: 
               <INPUT NAME="Foo1" TYPE="TEXT" SIZE="2">
              <INPUT NAME="Submit" TYPE="BUTTON" VALUE="Submit">
              </FORM>
              </BODY>
              </HTML>

Basically, what the script in listing 13.14 does is it presents a page with a small text entry box with a submit button. When the user clicks on the Submit button it triggers the Submit_OnClick event. VBScript knows to execute the Sub upon this trigger and it checks to see if the value in Foo1 is numeric. If it is numeric, it further checks to see if the value is between 100 and 1000, whereupon it gives a dialog box based on that value. If the number is not numeric it presents a dialog box asking the user to type in another value. Notice that the value is not really sent anywhere from the form. If you want the value to actually be sent back to the server you could use Document.myForm.Submit.

VBScript is similar to JavaScript in that it is very useful for checking form data for errors or omissions on the client machine (in the web browser instead of the server). Using OLE controls, you can even pass data into a control via a form and add or change that control's attributes or behavior.

VBScript Is Growing

In figure 13.1, you see the three tiers of Visual Basic, as well as how Visual Basic Scripting Edition (the long name for VBScript) fits in with the rest of the Visual Basic family of products.

Figure 13.1 : Visual Basic is offered in three versions, which are targeted at different levels of users.

At the bottom is VBScript: a free, small, and fast subset of Visual Basic that runs directly from Web pages. Next is Visual Basic for Applications, which is usually packaged with Microsoft Office. It features OLE automation and includes a debugger and script editor. At the top is Visual Basic 4.0, which is targeted at hard-core programmers, students, professionals, and hobbyists. It features client-server data access and distributed computing support, and it enables teams to create code using source control.

VBScript is a very new language specification. As of this writing, there is only one software implementation of it: Microsoft Internet Explorer version 3.0 Alpha. Microsoft has a client architecture called Sweeper, which is an API using Win32 and OLE to allow developers to add Internet capability to their applications. You will see other applications that begin to use Sweeper and as such will be able to read and interpret Visual Basic Script scripts. On the server side, Microsoft's Internet Information Server will also be using OLE and VBScript to automate many tasks as well as dynamic new capabilities.

As this language continues to develop, it will probably be targeted toward people who are already Visual Basic programmers and want to leverage their knowledge of VB to the Web. Further, Visual Basic Script is being developed as a language that will enable novice programmers to control a wide range of object types (specifically, Microsoft's OLE objects and Sun's Java applets). VBScript will also appeal as well to web site developers who seek to expand the interactivity of their site by using OLE controls for everything from small animations to complex full-blown Internet applications (like an inlined IRC client or a mini ftp client).

The specification will probably change considerably before it is ready for a final release-although unlike JavaScript, it is a subset of an already robust language that has been around for quite some time and will take advantage of that stability to seek wider acceptance than JavaScript.

Only time will decide which script language becomes more widely adopted, with VBScript having a huge following of Visual Basic programmers and JavaScript a very quickly growing base of Java programmers. As the spec is released, look for new additions to the Microsoft Visual Basic home page on the Web at www.microsoft.com/vbscript/.