Chapter 1. Introduction
Microsoft Visual Basic Scripting Edition, commonly known as VBScript, is a relative of the Visual Basic family, which includes the Microsoft Visual Basic Development System (the retail version of Visual Basic in its Enterprise, Professional, and Learning Editions) and Visual Basic for Applications (the language component of Visual Basic, which is included in the individual applications within Microsoft Office and Microsoft Project, as well as in a host of third-party applications).
VBScript is, for the most part, a subset of the Visual Basic for Applications programming language. It was developed so that the millions of Visual Basic developers could leverage their knowledge of VB/VBA in Internet scripting. One of the strengths of VBScript is that it uses the same familiar and easy syntax that has made VBA so popular as a programming language, making it very easy to learn for those who have some Visual Basic background. In addition, VBScript is fairly easy to learn for those without any programming experience.
Active Server Pages (ASP) applications
Windows Script Host (WSH) scripts
VBScript’s History and Uses
Version 1.0 of VBScript was initially introduced in Microsoft Internet Explorer (IE) 3.0, which was released in 1996. Its intended use at that point was to allow web page developers to enhance their pages through client-side scripting. In contrast to plain HTML, which supported the creation of static web pages only, the combination of HTML and client-side script allows the creation of web pages that are both interactive and responsive to the user. For instance, a script could allow the web page to display extended information about hyperlinks as the user’s mouse passes over them, or it could be used to validate data entered by the user without submitting it to the server. A script could even be used to generate a web page on the fly, without using any “hardcoded” HTML. The only limitation to VBScript as a language for client-side scripting was that VBScript could be used inside of Internet Explorer only (the only browser to support it) and thus was suitable only for use on corporate intranets that had standardized on Internet Explorer. Using VBScript for client-side scripting on Internet Explorer is discussed in Chapter 8.
Version 2.0 of VBScript was introduced in Internet Information Server (IIS) 3.0 in 1997. The most
notable additions to the language were “web-friendly” language
elements (such as lightweight Format... functions and the Filter, InStrRev, Reverse, and Join functions) that in most cases were
incorporated into the VBA language only with the release of VBA 6.0.
In addition, VBScript 2.0 added support for a number of intrinsic
constants to make code more readable and also implemented the
Const statement to allow user-defined
constants. Finally, the CreateObject and GetObject functions were added to
instantiate external COM objects; these functions, which are
inoperative in a client-side scripting environment, are essential for
supporting components that are capable of extending a scripted
This new version of VBScript was released with IIS to support server-side scripting using ASP. ASP is itself the object model exposed by IIS that allows your script to access information about the client’s request and to write to the server’s output stream. An ASP application consists of conventional web pages (that is, HTML and possibly client-side script written in any language) along with script that executes on the server. The output of an ASP script most commonly is HTML, which is simply inserted into the output stream returned by the server in response to a client request. This makes ASP important for several reasons. First, it can be used to produce output that is customized for the browser on which it’s displayed. Secondly, it provides a very strong web application environment, particularly one that takes advantage of backend processing. Along with ASP, Microsoft introduced ActiveX Data Objects (ADO) as its primary data access technology. Developing ASP applications with VBScript is discussed in Chapter 5.
Although IIS itself is language-independent and supports a number of available scripting languages, it is precisely in this realm—scripting for ASP—that VBScript quickly found its major application.
Version 3.0 of VBScript, released in 1998, had no new language features. Nevertheless, it was significant for marking the spread of VBScript beyond a scripted web environment. Besides IIS Version 4.0 and Internet Explorer Version 4.0, VBScript was now incorporated into Outlook 98 (an interim release of Outlook that was developed out of sync from the other applications in Microsoft Office) andWindows Script Host 1.0.
Microsoft Outlook was originally released in Office 97 as Microsoft’s entry into the personal information manager/workgroup messaging market. Outlook featured a number of forms to handle standard MAPI message types (such as messages, contacts, tasks, notes, and appointments) out of the box. However, VBScript made it possible to design new forms and customize their behavior. Although Outlook’s latest release,Outlook 2002, includes support for VBA, VBScript remains the programming language for Outlook 2002 forms. Developing Outlook forms with VBScript is covered in Chapter 6.
Version 4.0 of VBScript was also released as part of Visual Studio 6.0 in 1998. As in Version 3.0, no new language features were present. The difference was in the Microsoft Scripting Runtime Library (scrrun.dll ), which now included a File System object model as well as the Dictionary object introduced with VBScript 2.0. The addition of the object model made the library an essential component in any scripted environment.
Version 5.0, which shipped with Internet Explorer 5.0 and IIS
5.0 (which shipped with Windows 2000), added a number of new language
enhancements, including support for scripted classes using the
Class...End Class construct,
support for regular expression searches through the RegExp object, and
the ability to dynamically build expressions to be evaluated using the
Eval function or executed using
the Execute method.
As you can see, even though VBScript’s advent as a client-side scripting language was largely unsuccessful, Microsoft remained committed to VBScript as a “lightweight” form of VBA and continued to move the language forward. As a result, it came to be used in a number of environments other than client-side scripts, and in fact, has become one of the major scripting languages in use today.
What VBScript Is Used For: Gluing Together Objects
We’ve outlined the four major areas in which VBScript is used, but if we were to look at how scripts are written in each of these environments, we’d quickly note far more differences than similarities. (Because of this, we’ve devoted a separate chapter to each area in which VBScript is commonly used.) Yet this is misleading. If we take a more high-level view, we can see that the role of VBScript and the role of the environment in which its scripts are run are broadly similar, regardless of the environment’s unique features.
Typically, scripting languages are described as “glue” languages. That is, they are used to glue things together. That means that the glue itself does relatively little—it simply binds the rest of the script together. The “things” that the scripting language binds together are components or objects—that is, the objects exposed by the environment for which the script is being written (like ASP, Internet Explorer, Outlook, or WSH), as well as objects that are exposed by external applications, environments, or components (such as ActiveX Data Objects, Collaboration Data Objects, Microsoft Word, Microsoft Excel, or custom components created in Visual Basic). A map of a single high-level object (such as the Microsoft Word application, for instance, which is represented by the Application object) along with its child objects is known as an object model .
One type of object model that’s particularly suitable for scripting is shown in Figure 1-1. In this particular case, the figure shows the ASP object model. Two features that are particularly noteworthy are its flatness and its lack of interdependence. (Contrast it, for example, with the Microsoft Word object model, a portion of which is shown in Figure 1-2.) In particular, a flatter object model and/or one whose objects have a fair degree of independence has a number of advantages:
- Ease of navigation
Since the object model is flat, you don’t have to be concerned with navigating upward and downward through the object hierarchy. This makes coding easier, reduces the time spent debugging, and improves performance.
- Ease of instantiating objects
Since objects are independent of one another, you can easily create them or retrieve a reference to them, instead of having to figure out which portion of the object model you must navigate to in order to instantiate that object, or which property or method you must call that returns that object.
Individual objects within an object model expose properties, methods, and events. We’ll discuss each of these in turn.
Properties are attributes or values of an object that can be
read and set. (In other words, properties are variables that belong
to an object.) As long as the value returned by the property is not
an object, setting and retrieving property values requires a simple
assignment statement. For example, the following line of code stores
the value of the ASP Session object’s TimeOut property to a variable
lTimeOut = Session.TimeOut ' Retrieve property value
Storing a new value to the property is just as easy. For instance, the following line of code changes the value of the Session object’s TimeOut property to 10 minutes:
Session.TimeOut = 10 ' Set property value
Some properties are read-only; that is, while you can retrieve a property’s value, attempting to set it is not permitted and generates an error. For example, the code:
lSVars = Request.ServerVariables.Count ' Read-only property
assigns the count of the number of variables in the Request
object’s ServerVariables collection to a variable named
lSVars. Attempting to set the value of
the Count property, however, generates an error, since the property
(as well as the ServerVariables collection itself) is read-only.
Rarely, you may also encounter properties that are write-only, or
that are write-only under certain conditions; you can set the
property’s value, but you can’t retrieve it. Typically, this is done
for security reasons.
Many properties return either individual objects or
collections. (A collection is an object that serves as a container
for other data items or objects.) These also require assignment
statements that use the
statement. For example, you can retrieve a reference to the root
folder of the C: drive on a
local system with a code fragment like the following:
Set oFS = CreateObject("Scripting.FileSystemObject") Set oFolder = oFS.Drives.Item("C").RootFolder
Note that in the second line of code, we navigate the File System object model from its top-level object, the FileSystemObject object, to the Drives collection object. We use the collection’s Item property to retrieve a reference to the Drive object representing Drive C:, and then retrieve the value of its RootFolder property to get a reference to an object representing the drive’s root folder.
Methods are simply public functions or subroutines exposed by an object. You call them in the same way that you call any function or subroutine, except that you must preface the method name with a reference to the object whose method you are calling. If you are calling a subroutine or a function whose return value does not interest you, you can use syntax like:
which calls the ASP Response object’s Write method to write
the beginning of a web page to the server’s output buffer in
response to a client request. To call a method that returns an
object, use an assignment statement along with the
Set statement and enclose the argument
list in parentheses. For example:
Set oShell = WScript.CreateObject("WScript.Shell") Set oShortcut = oShell.CreateShortcut("My First Script.lnk")
is a fragment from a WSH script that creates a shortcut and
returns the WshShortcut object representing that shortcut. If the
method returns an ordinary value, the
Set statement must not be used. For
instance, the second line of the code:
Set oFS = CreateObject("Scripting.FileSystemObject") strTempFile = oFS.GetTempName( )
calls the FileSystemObject object’s GetTempName method to
retrieve a temporary filename, which is stored to the variable
strTempFile. The opening and closing
parentheses after the method name are optional, since the method in
this case takes no arguments.
Methods are routines belonging to an object that we call in code. Event handlers , on the other hand, are functions or subroutines that we write that are called by the VBScript engine in response to some event that occurs to the object. For instance, when an ASP application is accessed for the first time, its OnStart event is fired. If we have included code like the following in our global.asa file:
Sub Application_OnStart ' application startup code goes here End Sub
Differences Between VBScript and VBA
VBScript is a subset of the Visual Basic for Applications language. There are several features that VB and VBA programmers have become accustomed to that are not present in VBScript. This does not lessen the usability of VBScript: it only serves to reinforce that VBScript is meant for scripting and not full-blown client/server application development or COM component development. Let’s take a look at a few of the larger differences between VBScript and VBA:
- VBScript is a weakly typed language.
Unlike Visual Basic and Visual Basic for Applications, in which the developer can define the data type of a variable in advance, all variables in VBScript are variants. There are types to handle different types of data; you can use these as you would the traditional data types in Visual Basic. For more information, see Chapter 3.
- VBScript does not support early binding.
Because variables are untyped and code is not compiled, all external objects instantiated in VBScript code are necessarily late-bound. This has a number of implications. First, late binding typically entails a substantial performance penalty in comparison to early binding. Second, while the properties and methods of early-bound objects can be examined in Visual Basic or hosted VBA environments using the Object Browser, this is not the case with late-bound objects. Finally, the help facilities available for early-bound objects in VB and VBA (like Auto List Members and Auto Quick Info) are not available, making syntax errors more likely and ready access to good documentation all the more necessary.
- VBScript does not support named arguments.
VBA supports both positional and named arguments for most functions and procedures. For example, the VBA MsgBox function can be called using positional arguments as follows:
lResult = MsgBox("Delete this file?", _ vbYesNo Or vbQuestion Or vbDefaultButton2, _ "Confirm File Deletion")
A method call using named arguments takes the following form:
lResult = MsgBox(Prompt:="Delete this file?", _ Title:="Confirm File Deletion", _ Buttons:=vbYesNo Or vbQuestion Or vbDefaultButton2)
Note that while positional arguments must occur in a predefined sequence, named arguments need not. At least in our experience, more advanced programmers tend to prefer positional syntax, while more novice programmers tend to prefer named arguments.
- VBScript does not have an IDE.
There is no integrated development environment for VBScript that parallels the IDE for Visual Basic and Visual Basic for Applications. Development tools are available for all of the environments in which VBScript is used, but all fall short of the power, simplicity, elegance, and ease of use of the VB/VBA IDE.Typically, web developers have had their own environments for writing their code. VBScript for the Web, whether it is client-side or server-side, is embedded inside of a
<SCRIPT>tag. This allows web developers to continue to use their tool of choice even when using VBScript; a wide array of tools for web script development are available. Scripts for WSH can be created with the use of a simple text editor like Windows Notepad. Outlook comes with its rudimentary IDE (a glorified version of Notepad) for attaching code to Outlook forms.
We should also mention one difference between VBScript and VB/VBA that developers and commentators often emphasize—namely, that VBScript is slower than VB/VBA. This contention, though, raises more questions than it answers. First, if VBScript is used as “glue code,” as it typically is, then the limiting factor in a VBScript program’s performance will be the components it consumes, rather than theperformance of the script itself. Second, performance cannot be measured in a vacuum. Rather than asking whether VBScript is faster or slower in the abstract, we have to consider the particular tasks for which it is being used.
But practically speaking, “Which is faster?” is usually the wrong question. The right question to ask is, “Which is fast enough?”, which is a very different question. “Which is faster?” is a bad metric to use when choosing or comparing programming languages. Many factors influence performance, and not all are obvious. Code reliability, maintainability, robustness, and cost of development are all important factors to be considered along with performance.
Performance (“faster” and “slower”) is also inherently hard to measure, since the terms themselves are more subjective than objective. Do they refer to “UI snappiness,” “time to first byte,” “throughput,” or “page faults per second,” or to something else?
As a programming language, VBScript offers acceptable performance along with an elegance and simplicity that make it a valuable tool for the range of scripted applications for which it was developed.