Tải bản đầy đủ (.pdf) (618 trang)

Wrox VBScript programmers reference dec 1999 ISBN 0764543679 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.34 MB, 618 trang )


Table of Contents
VBScript Programmer's Reference...................................................................................................................1
Introduction.........................................................................................................................................................6
Who is this Book For?............................................................................................................................6
How to Use this Book.............................................................................................................................6
What is VBScript?..................................................................................................................................7
What Can You Do With VBScript?......................................................................................................11
What Tools Do You Need to Use VBScript?.......................................................................................14
What's New in VBScript 5?..................................................................................................................15
Code Conventions.................................................................................................................................17
Tell Us What You Think.......................................................................................................................17
Customer Support.................................................................................................................................18
Chapter 1: A (Very) Short Introduction to Programming..........................................................................19
Overview...............................................................................................................................................19
Variables and Data Types.....................................................................................................................19
Control of Flow.....................................................................................................................................23
Operators...............................................................................................................................................31
Organizing and Reusing Code..............................................................................................................32
Top−Down vs. Event Driven................................................................................................................35
Some Guidelines to Keep in Mind........................................................................................................37
Suggestions for Further Reading..........................................................................................................39
Chapter 2: Variables and Data Types............................................................................................................40
The Visual Basic Data Types................................................................................................................40
The Variant: VBScript's Only Data Type.............................................................................................42
Variables in VBScript...........................................................................................................................60
Literals and Named Constants..............................................................................................................65
Complex Data Types.............................................................................................................................69
Chapter 3: Control of Flow.............................................................................................................................77
Branching Constructs............................................................................................................................77
Loop Constructs....................................................................................................................................81


Chapter 4: Error Handling, Prevention and Debugging.............................................................................93
Overview...............................................................................................................................................93
Introduction...........................................................................................................................................93
Seeing the Error of your Ways..............................................................................................................94
Different Types of Errors......................................................................................................................98
What Can We Do About Errors?........................................................................................................105
Debugging...........................................................................................................................................120
Common Errors and How To Avoid Them........................................................................................127
Summary.............................................................................................................................................128
Chapter 5: Using COM Components and Objects.....................................................................................129
Overview.............................................................................................................................................129
Introduction to COM components and Objects..................................................................................129
Object and Object Interfaces...............................................................................................................131
What COM Components and Objects are Available?........................................................................137
Objects and the Variant data type.......................................................................................................138
i


Table of Contents
Chapter 5: Using COM Components and Objects
Properties and Methods.......................................................................................................................139
Object Scope, Lifetime and References..............................................................................................141
Using the With Statement with Objects..............................................................................................145
Create your own COM Objects...........................................................................................................146
Summary.............................................................................................................................................146
Chapter 6: Using COM Components with MTS.........................................................................................147
Overview.............................................................................................................................................147
A Quick Introduction to MTS.............................................................................................................147
Advantages of using MTS..................................................................................................................149
Next Step: COM+...............................................................................................................................158

Summary.............................................................................................................................................160
Chapter 7: The Built−In and Scripting Runtime Objects..........................................................................162
Overview.............................................................................................................................................162
Runtime vs. Built−In − What's the Difference?..................................................................................162
Built−In Objects..................................................................................................................................162
Regular Expressions............................................................................................................................163
Scripting Runtime Objects..................................................................................................................173
Summary.............................................................................................................................................182
Chapter 8: Classes in VBScript (Writing Your Own COM Objects).......................................................183
Classes vs. Objects vs. Components...................................................................................................183
Chapter 9: Windows Script Components....................................................................................................204
What Are Windows Script Components?...........................................................................................204
What Tools Do You Need?.................................................................................................................204
The Script Component Runtime.........................................................................................................205
Script Component Files......................................................................................................................206
Exposing Properties, Methods, and Events.........................................................................................211
Creating Registration Information......................................................................................................214
Creating the Script Component Type Library....................................................................................216
Interface Handlers...............................................................................................................................218
Compile−time Error Checking............................................................................................................220
Using VBScript Classes in Script Components..................................................................................220
Summary.............................................................................................................................................227
Chapter 10: The Windows Script Host........................................................................................................228
Overview.............................................................................................................................................228
What Tools Do You Need?.................................................................................................................228
What is the Windows Script Host?.....................................................................................................229
Running Scripts with Windows Script Host.......................................................................................230
Using .WSH Files to Launch Scripts..................................................................................................232
Windows Script Host Intrinsic Objects...............................................................................................232
Summary.............................................................................................................................................263

Additional Resources..........................................................................................................................263

ii


Table of Contents
Chapter 11: General Client−Side Web Scripting.......................................................................................265
What Tools Do You Need?.................................................................................................................265
How Browser Scripting Works...........................................................................................................265
The Various Scripting Languages − What's Best for the Browser.....................................................266
Responding to Browser Events...........................................................................................................268
Validating Forms................................................................................................................................272
The Document Object Model..............................................................................................................276
Summary.............................................................................................................................................280
Chapter 12: High−Powered Client Scripting..............................................................................................282
Technology Requirements..................................................................................................................282
Importance of Browser Security Settings...........................................................................................282
Scriptlets − Ancestors of Behaviors....................................................................................................282
Managing Events................................................................................................................................288
Behaviors............................................................................................................................................292
HTML Components............................................................................................................................295
Remote Scripting................................................................................................................................304
Summary.............................................................................................................................................310
Chapter 13: HTML Applications (HTAs)...................................................................................................311
What Tools Do You Need?.................................................................................................................311
What is an HTML Application?.........................................................................................................311
How to Create a Basic HTA...............................................................................................................312
The <HTA:APPLICATION> Tag......................................................................................................314
HTAs and Security..............................................................................................................................320
HTA Deployment Models...................................................................................................................324

What Isn't Supported With HTAs?.....................................................................................................326
Summary.............................................................................................................................................327
Chapter 14: Server−Side Web Scripting With ASP...................................................................................328
Overview.............................................................................................................................................328
The Anatomy of the HTTP Protocol...................................................................................................328
Introducing Active Server Pages........................................................................................................333
The Active Server Pages Object Model..............................................................................................336
Using Active Server Pages Effectively...............................................................................................352
Summary.............................................................................................................................................358
Chapter 15: Talking to Databases: ActiveX Data Objects.........................................................................359
What Tools Do You Need?.................................................................................................................359
The Evolution of ADO........................................................................................................................359
What Are ActiveX Data Objects?.......................................................................................................360
The ADO Objects...............................................................................................................................361
Summary.............................................................................................................................................374
Chapter 16: Microsoft Script Control..........................................................................................................375
Why Script your Application?............................................................................................................375
What tools do you need?.....................................................................................................................376
Adding Script Control to VB Application..........................................................................................377
Macro and Scripting Concepts............................................................................................................380
The Script Control Object Model.......................................................................................................381
iii


Table of Contents
Chapter 16: Microsoft Script Control
Other Scripting Elements....................................................................................................................396
Error Trapping with Script Control.....................................................................................................397
Sample Applications...........................................................................................................................399
Summary.............................................................................................................................................408

Appendix A: Visual Basic Functions and Keywords..................................................................................409
Overview.............................................................................................................................................409
Operators.............................................................................................................................................409
Math Functions...................................................................................................................................417
Date and Time Functions and Statements...........................................................................................422
Unsupported Array Functions and Statements...................................................................................435
Unsupported String Functions, Statements and Constructs................................................................449
String Constants..................................................................................................................................451
Conversion Functions.........................................................................................................................451
Unsupported conversion functions.....................................................................................................456
Miscellaneous Functions, Statements and Keywords.........................................................................457
Appendix B: Differences between VB/VBA and VBScript5......................................................................471
Appendix C: Code Conventions...................................................................................................................474
Variable Naming Conventions............................................................................................................474
Procedure Naming..............................................................................................................................475
Indentation..........................................................................................................................................475
Commenting........................................................................................................................................476
Appendix D: Visual Basic Constants Supported in VBScript...................................................................477
Color Constants...................................................................................................................................477
Date and Time Constants....................................................................................................................477
Date Format Constants........................................................................................................................478
Miscellaneous Constants.....................................................................................................................478
MsgBox Constants..............................................................................................................................478
String Constants..................................................................................................................................479
Tristate Constants...............................................................................................................................479
VarType Constants..............................................................................................................................479
Appendix E: VBScript Error Codes and the Err Object...........................................................................481
Runtime Errors....................................................................................................................................481
Syntax Errors......................................................................................................................................482
Err Object and On Err statement.........................................................................................................484

Appendix F: The Scripting Runtime Library Objects Reference.............................................................494
The Scripting.Dictionary Object.........................................................................................................494
The Scripting.FileSystemObject Object.............................................................................................495
The Scripting.TextStream Object.......................................................................................................500
Appendix G: Windows Script Host 2.0........................................................................................................502

iv


Table of Contents
Appendix H: The Browser Object Model IE4............................................................................................514
The Object Model In Outline..............................................................................................................514
HTML and Form Controls Cross Reference.......................................................................................530
Appendix I: The Browser Object Model IE5.............................................................................................533
The Object Model In Outline..............................................................................................................533
HTML and Form Controls Cross Reference.......................................................................................545
Appendix J: The Integral ASP Objects.......................................................................................................548
The ASP Object Model.......................................................................................................................548
The Application Object.......................................................................................................................549
The ASPError Object..........................................................................................................................550
The Request Object.............................................................................................................................550
The Response Object..........................................................................................................................551
The Server Object...............................................................................................................................553
The Session Object.............................................................................................................................554
Appendix K: ADO Object Summary, Constants, and Data Types...........................................................557
Microsoft ActiveX Data Objects 2.5 Library Reference....................................................................557
ADO Constants...................................................................................................................................571
ADO Data Types.................................................................................................................................605
Appendix L: The Microsoft Script Encoder................................................................................................611


v


VBScript Programmer's Reference
Susanne Clark,
Antonio De Donatis,
Adrian Kingsley−Hughes,
Kathie Kingsley−Hughes,
Brian Matsik,
Erick Nelson,
Piotr Prussak
Daniel Read,
Carsten Thomsen,
Stuart Updegrave,
Paul Wilton
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2003 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
Library of Congress Card Number:
ISBN: 0−7645−4367−9
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1B/QZ/QW/QT/1N
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by
any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under
Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of

the Publisher, or authorization through payment of the appropriate per−copy fee to the Copyright Clearance
Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750−8400, fax (978) 646−8700. Requests to the
Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475
Crosspoint Blvd., Indianapolis, IN 46256, (317) 572−3447, fax (317) 572−4447, E−Mail:

Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in
preparing this book, they make no representations or warranties with respect to the accuracy or completeness
of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a
particular purpose. No warranty may be created or extended by sales representatives or written sales materials.
The advice and strategies contained herein may not be suitable for your situation. You should consult with a
professional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any
other commercial damages, including but not limited to special, incidental, consequential, or other damages.

1


VBScript Programmer's Reference
For general information on our other products and services or to obtain technical support, please contact our
Customer Care Department within the U.S. at (800) 762−2974, outside the U.S. at (317) 572−3993 or fax
(317) 572−4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not
be available in electronic books.
Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, the Wrox Programmer to Programmer
logo and related trade dress are trademarks or registered trademarks of Wiley in the United States and other
countries, and may not be used without written permission. All other trademarks are the property of their
respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this
book
Trademark Acknowledgements
Wrox has endeavored to provide trademark information about all the companies and products mentioned in
this book by the appropriate use of capitals. However, Wrox cannot guarantee the accuracy of this

information.
Credits
Authors
Daniel Read
Susanne Clark
Antonio De Donatis
Adrian Kingsley−Hughes
Kathie Kingsley−Hughes
Brian Matsik
Erick Nelson
Piotr Prussak
Carsten Thomsen
Stuart Updegrave
Paul Wilton
Technical Reviewers
Chris Behrens
Steve Danielson
John Granade
Michael Harris
Richard Harrison
Dan Pfeffer
Nic Roche
Design / Layout
Tom Bartlett
Mark Burdett
William Fallon
Jonathan Jones
John McNulty

2



VBScript Programmer's Reference
Additional Material
Jerry Ablan
Jeff Hart
Alex Homer
David Sussman
Chris Ullman
Illustrations
William Fallon
Jonathan Jones
Editors
Gregory Beekman
Lums Thevathasan
Robert Shaw
Devin Lunsford
Cover Design
Chris Morris
Project Manager
Chandima Nethisinghe
Managing Editor
Victoria Hudgson
Index
Martin Brooks
Development Editor
Peter Morgan
About the Authors
Daniel Read
Daniel Read is Senior Developer at Compass, Inc. in Atlanta, GA, where he and fellow team members build

IIS/ASP/VB/MTS e−commerce web sites, as well as client/server and distributed systems. Daniel sometimes
longs for his simpler, statically linked days as an X−Base developer and DOS command line junkie, but today
enjoys the power afforded by the arsenal of Microsoft's Windows DNA tools and technologies. His other
interests include camping, crime fiction, listening to music of all sorts, and going to as many concerts as he
can. He's not sure if co−authoring a programming book will help him meet the woman of his dreams, but it
sure would be nice.
Carsten Thomsen
Carsten Thomsen is a Microsoft Certified Systems Engineer, who started programming in Visual Basic back
in 1993, when it was version 3.0. Presently he is pursuing Microsoft Certified Systems Developer certification
and was recently awarded the MVP title for his contributions to the Microsoft Visual Basic newgroups. For
the last 4 years he has been developing 2−tier and 3−tier client/server solutions based on MS SQL Server,
MTS and MSMQ, but has more recently been moving towards browser−based development, based on MS IIS,
3


VBScript Programmer's Reference
using ASP/VBScript, COM/ActiveX components and Visual Basic WebClasses.
In whatever spare time he has, he enjoys traveling and spending time with his two daughters, Nicole and
Caroline, and his girlfriend Mia. He works out at a local gym and (at spectator−level) enjoys ice hockey and
soccer. He is generally considered a computer freak, and spends too much time at the computer.
Piotr Prussak
Piotr Prussak works for ACEN in Buffalo, NY as a developer (although he is originally from Poland). He
creates ASP, VB and Java Applications for the company and its clients. He also spends some time working
with the SQL server and ColdFusion, probably more than he should. When he's not programming and
mentoring, he either writes stuff, or edits stuff written by others. Sometimes he sleeps, eats and relaxes like
any other human being. In a past life he used to be a photographer, but that was just too relaxing.
Piotr (or Peter, as some might call him) is married to lovely Joanne, who is an MIS student at a local
University. Sometimes they travel all over the world and are disconnected from the world of computers and
24 hour news.
Brian Matsik

Brian Matsik is the President and Senior Consultant at OOCS in Charlotte, NC. He is MCSD certified and has
been working with Visual Basic, VBScript, and VBA for over six years. He currently specializes in ASP, SQL
Server, and VB COM. Brian can be reached at
Brian would like to thank Tracy for her support, Mike Dunner for keeping him on his toes when it comes to
ADO and MTS, and Mark Harris for taking care of the books while he stays glued to the PC.
Paul Wilton
After an initial start as a Visual Basic applications programmer, Paul found himself pulled into the net and has
spent the last 18 months helping create internet and intranet solutions.
Currently he is developing web−based systems, primarily using Visual Basic 6 and SQL Server 7, along with
numerous other technologies.
Paul would like to wish lots of love to his fiancée Catherine, who ensures his sanity chip remains plugged in.
Antonio De Donatis
Antonio De Donatis () began programming in 1984, using a mixture of Basic and
assembler on a Commodore 64. Since then, he has designed software the object−oriented way, employing
more programming languages and technologies than he can count. He finds programming to be one of the best
activities to exercise creativity and to be intellectually active. He has worked for many of the major firms in
IT either as employee or as freelance. His current interests include all the technologies involved in the design
and implementation of e−commerce solutions. Antonio holds a BS degree in Computer Science from Pisa
University (Italy) and he is a Microsoft Certified Professional.
Susanne Clark
Susanne has worked with the latest internet technologies, including DHTML, XML, XSL, IE5 programming
and scripting, and has contributed chapters on these subjects to the recently published Professional Visual
4


VBScript Programmer's Reference
InterDev 6 Programming from Wrox Press. She is currently working as a user interfaces developer in Seattle,
USA. When not dealing with computers, she enjoys spending time with her cats, and reading mystery books.
Susanne would like to thank Luca for all of his patience and help. Ti amo.
Adrian Kingsley−Hughes

Adrian Kingsley−Hughes is Technical Director of Kingsley−Hughes Development Ltd., a UK−based training
and development firm, where he is a consultant in Internet Development and Windows platform
programming. He has co−authored 8 books for Active Path and Wrox Press. His abiding passion is the Search
for Extra Terrestrial Intelligence and he is the Welsh Regional Coordinator for SETILeague Inc. In his spare
time he writes horror novels, plays the didgeridoo and is currently building a radio telescope in his back yard.
Kathie Kingsley−Hughes
In addition to writing web development books for Active Path and Wrox Press, Kathie Kingsley−Hughes is
the Managing Director of UK−based Kingsley−Hughes Development Ltd., where she specializes primarily in
the development and delivery of training courses in web development skills. She began teaching in 1985 and
has lectured at several UK colleges and other training establishments and she is currently teaching at ZDU.
Any spare time is taken up with astronomy, photography and hiking in the mountains.
Eric Nelson
Erick Nelson is an 18 year old Internet developer and programmer, and creator of the award winning website
cues.com. about which he spoke at both the 1998 and 1999 Professional ASP Developer's Conference. Erick
began his programming career at age 16, and now has experience using ASP, VBScript and Visual Basic to
design sites.
Erick enjoys playing computer games and working on his online RPG system. His outdoor activities include
mountain biking, swimming, cliff jumping, playing tennis and snow skiing. He can be reached at

Erick would like to thank his Mom, Cindy Cashman, for helping him start his business, and his Dad, Mark
Nelson, for teaching him how to build things and raising him better than anyone could under the
circumstances. Thanks must also go to Bill Stroud and Charlie Bass.

5


Introduction
The aim of this book is to provide an introduction to, overview of, and reference for:
• The VBScript 5 language
• The many 'contexts' in which the VBScript language can exist and be useful

Our first goal probably seems pretty straightforward: we're going to cover what you need to know to write
VBScript code. We'll go over general syntax, functions, keywords, style, error handling, and similar
language−specific topics. However, VBScript the language is of limited use without something to do. That's
where the scripting contexts (or hosts) come in.
Microsoft has done an excellent job over the last couple of years in building robust support for scripting into
the Windows operating systems (Windows 95/98, Windows NT, and now, Windows 2000). Support for
scripting is an important aspect of a mature operating system environment. 'support for scripting' simply
means that the operating system provides a mechanism through which users can write programs in a scripting
language, such as VBScript. A scripting language differs from 'normal' programming languages in some key
ways, which we will discuss in this introduction. Scripting allows you to extend the capabilities of an existing
computer environment. This book will provide you with the knowledge you need to leverage all of this
dormant power.

Who is this Book For?
VBScript, and this Programmer's Reference book, can be extremely useful to all sorts of information
technology professionals, and even for the casual user who wants to automate some common tasks or learn a
little bit about the art and science of programming. For example:
• Network administrators can use VBScript with the Windows Script Host to write powerful login
scripts and automate formerly time−consuming and error−prone tasks all without using clumsy DOS
batch files
• Application developers can use VBScript to extend their Windows applications with powerful macro
and customization features
• Web developers and designers can use VBScript with DHTML to create amazing browser−based and
stand−alone HTML Applications
• Web application developers can use VBScript to create dynamic, high−performance web sites with
Internet Information Server and Active Server Pages
These are just examples the full range of people and tasks for which VBScript can be useful cannot be
expressed in a single paragraph. If you're not sure if this book is for you, or if VBScript can help you, please
read on because VBScript can do a lot more than you might think.


How to Use this Book
This book is divided up into three parts. Part 1 covers the VBScript language the keywords, functions, syntax,
etc. For those who are new to writing code, Part 1 also includes a very short introduction to programming.
Advanced readers might not need to read Part 1 straight through, but should probably read the chapters on
VBScript's new support for classes and Windows Script Components, a very exciting new technology.

6


What is VBScript?
Part 2 covers what we call 'VBScript in Context.' Although powerful in its own right, the VBScript language
derives its real power from:
• The hosts that support it such as the Windows Script Host (formerly known as the Windows
Scripting Host) and Active Server Pages
• The objects that are made available to it, such as the Scripting Runtime Objects and Active Data
Objects
You'll learn, among lots of other things, how to create an HTML Application and how to write a scriptlet and
attach it to a DHTML behavior.
At the end of the book there is a large set of appendices, which cover things such as naming conventions, the
syntactic differences between Visual Basic and VBScript, and the object models that are important to
VBScript developers. Although the chapters will cover these object collections in detail, the object diagrams
provide a very helpful high level view of the objects and their properties and methods. Appendix A also
contains a complete reference to the functions, keywords, and operators of the VBScript 5 language.
Finally, don't forget that we, at Wrox, offer comprehensive on−line support and references.
www.webdev.wrox.co.uk has an HTML listing and www.asptoday.com is a dedicated ASP resource center.
Important

Advanced readers who are already familiar with VBScript and the concept of a scripting
language might want to skip these introductory sections. However, if you are not yet
familiar with all of the new features of VBScript 5 and with the new types of solutions

supported by Microsoft's latest scripting hosts, you might want to take a look at the
What Can You Do With VBScript? and What's New in VBScript 5 sections of this
Introduction.

What is VBScript?
As its name suggests, VBScript is what's known as a scripting language. How is a scripting language
different from other types of programming languages? One big difference is the point at which the code you
have written is 'compiled'.

A Little Background
All programming languages are compiled at some point otherwise the computer would not be able to respond
to their commands. As you undoubtedly know, at the lowest level, the language of a computer is broken down
into a series of 1's and 0's. This ones−and−zeroes language is also known as binary or machine language.
Different combinations of 1's and 0's mean different things to the low−level hardware of the computer. One
binary arrangement of 1's and 0's might mean add these two numbers together. Another might mean, store this
value in such−and−such a memory address. This is an oversimplification, but hopefully you get the idea. It's
pretty amazing, but all of the different things you can ask a computer to do are ultimately broken down into a
fairly small set of machine language commands.
There was once a time when programmers had to write computer programs in binary as you might imagine,
this is pretty difficult. Over time, more advanced programming languages were developed, each of which
added ever−higher levels of abstraction, so that programmers could use syntax that was a little closer to the
English language. However, even as programming languages have become increasingly abstract, the computer
hardware has continued to understand only machine language.

7


What is VBScript?

Scripting Languages are Compiled Later than Other Languages

Compilation is the process of turning the higher−level language into the binary that the computer
understands. The difference with 'normal' languages and scripting languages is not whether they are compiled
but when. Languages like C and C++ are commonly known as compiled languages. This may seem a bit
confusing since we just said that all languages are ultimately compiled, but they are called this because they
are compiled down to machine code at design time. That is, the programmer writes the code, then issues a
command to a special program called a compiler to compile the code down to machine language.
A scripting language, on the other hand, is 'compiled' (or more precisely, 'interpreted') at runtime, which
means that until it is executed, the script remains a plain text file. If you looked at a compiled C program, it
would not make any sense, because it's been broken down into machine language. However, a script is always
stored as a plain text file. You can write and read the script in plain text, change it at will, and just tell a script
engine to run it. You do not have to go through a separate design−time step to compile the program. Certainly,
there are special formatting conventions that you must follow when you write a script, but the code itself
always remains plain text that you can read and edit in any text editor (such as the Notepad application that is
included with all Windows versions).
A script is compiled at runtime by a scripting engine, which is a special program that knows how to interpret
the text you type into the script and turn it into commands that the computer can understand. In this respect, it
is not unlike the C programmer's design−time compiler.
Compiling a program at design time affords three major advantages, which, conversely, translate into
disadvantages for a scripting language such as VBScript:
• A compiled program will run much faster when executed. This is because it has already been
translated into machine language. Since the translation step does not need to take place every time the
program is executed, it will run faster than a script that must be compiled at runtime, every single time
it is run.
• Once translated into machine language, a compiled program cannot be changed. This protects the
intellectual property of the developer or company that owns the program because it is compiled into a
form that is unreadable. A curious user or malicious hacker cannot read the code and see how the
developer achieved their results, or 'borrow' parts of the code for their own. Since a script is plain text,
anyone who can gain access to the text file can read it. Some scripts, such as those embedded in
Active Server Pages (which are a combination of HTML and script), are not normally available to the
user to see because they reside on the server, and the web server prevents them from being

downloaded directly. However, other kinds of scripts, such as those embedded in a client−side web
page or a Windows Script Host file that a network administrator places on everyone's machine, can be
opened, read, and easily copied.
Important

Ironically, this apparent transparency disadvantage has helped scripting achieve huge
gains in popularity in recent years. Since you can find script code all over the web, it's
relatively easy for people to find it, read it, copy it, and learn from it. Microsoft has
developed a new technology for Internet Explorer 5, called script encoding, that helps
web script developers protect their intellectual property.
• A compiler catches syntax errors at design time but syntax errors in a script cannot be caught until
runtime. Even expert programmers make syntax mistakes when they write code. Both a design−time
compiler and a runtime script engine expect the code you write to follow certain rules of syntax. For
example, if you call a function that displays a message to the user, you must use the proper name for
the function, and pass the parameters that the function expects in the proper order. If you don't do this,
the compiler or script engine will complain at you. With a compiled language, such inevitable
8


What is VBScript?
mistakes are caught at design time, and the compiler won't compile the program until the programmer
fixes them. However, since a scripting language is not compiled until runtime, syntax errors might
slip through for your users to see.
Script languages have the following advantages over compiled languages:
• Script code can be embedded as plain text with other types of code, such as HTML, XML, and scripts
written in different languages. The classic example of this is web scripting, in which you can mix
scripts in different languages (which provide functionality) with HTML (a 'markup' language which
handles presentation) and XML (another markup languages that handles data structure) all in the same
file. This mixture of plain−text script code, HTML, and XML can be downloaded very quickly into a
web browser, at which time it is executed. While you can do this with a compiled language, such

solutions are usually proprietary in nature and don't work in different brands of browsers.
• Script code is very good for quick, ad−hoc solutions. You can whip out a simple script to solve a
simple problem in no time. For example, if you wanted to backup several groups of files stored in
different directories on different drives, you could write a simple script that would find these files and
compress them into an archive file. You could, of course, also do this by hand. However, if this were
a task that you needed to repeat on a regular basis, writing a script to perform the task for you would
probably make repetitions of the task faster and more reliable.
• Since scripting does not require a complicated Integrated Development Environment (IDE), such
as those used by Visual Basic and C++ programmers, a scripting language is generally easier to learn.
For a person new to software construction, scripting can be a great entryway into the vast world of
programming. Scripting languages are generally more forgiving than compiled languages, and, as
we've mentioned, they're ideal for automating simple tasks. VBScript, with its roots in the BASIC
programming language, is especially easy for a non−programmer to learn.

VBScript, Visual Basic, and Visual Basic for Applications
Microsoft is famous for unleashing myriad acronyms and often confusing terms and phrases onto the world,
and you'll encounter plenty of these in this book. This includes the alphabet soup of VBScript (VBS), Visual
Basic (VB), and Visual Basic for Applications (VBA). The distinction between these three can be somewhat
confusing. Hopefully, we can make things a little clearer.
We'll start with Visual Basic of which both VBA and VBScript are subsets. Visual Basic is a stand−alone,
compiled language, with its own Integrated Development Environment (IDE), which includes a language
editor, debugger, form designer, project manager, source code control integration, wizards, and other features
that facilitate application development. Visual Basic is typically used to develop stand−alone, compiled
applications and components. VB provides a full set of language features, including the ability to access the
Windows API, which is a set of low−level functions that allow an application to directly access the
functionality of the Windows operating system.
Important

It is not exactly correct to call Visual Basic a 'compiled' language. It is more like a hybrid
between a compiled language and an interpreted language. VB applications are compiled, but

rely on a large 'runtime library', which is a set of DLLs that must be installed in order for the
compiled VB application to run. VB applications can also be compiled to interpreted 'P−Code',
which is a kind of intermediate compilation step that still requires some compilation at runtime
(and is therefore slower). However, since version 5 of Visual Basic brought 'real' compilation to
VB, few VB developers compile to P−Code any longer.
Finally, to add to the confusion, although VBA is, in terms of functionality, considered a sub−set
of Visual Basic, VB actually uses VBA as its core. The VBA library defines the Visual Basic
9


What is VBScript?
language itself and allows other applications (such as Word and Excel) to add (or host) Visual
Basic capabilities. In a sense, the VB IDE is simply another one of these hosting applications.
Visual Basic for Applications is an 'embedded' version of Visual Basic. VBA can be integrated with an
existing application to provide a facility for customization and extension of the application that hosts VBA.
The best example of this is the Microsoft Office family of applications. Microsoft Word, Excel, and Access
(among others) all support VBA, and even provide a full−blown VBA Integrated Development Environment
similar to VB's stand−alone IDE. Using the VBA IDE, you can write Visual Basic code to provide rich
functionality that goes well beyond the basic word processing, spreadsheet, and database features provided by
these applications. Many of the same powerful language features of VB are available in VBA, the difference
being that VBA code can only live in the context of the hosting application. VBA can be compiled to
'P−Code' within the hosting application, which makes it faster than VBScript, but not as fast as fully compiled
VB applications and components.
Although VBScript is similar syntactically to VB and VBA, it is quite a different animal. Like VBA,
VBScript is also an embedded language and cannot be compiled into a stand−alone application or executable.
However, VBScript depends on a scripting host, which is a special application that knows how to compile and
execute plain−text VBScript code at runtime. Originally, Microsoft created VBScript as an alternative to
Netscape's JavaScript. Besides a simple desire to beat Netscape at their own game, Microsoft wanted to
provide a way for Visual Basic developers to embed script code in plain−text HTML pages, which can't be
done with design−time−compiled VB and VBA. Over time, Microsoft expanded support for VBScript beyond

simple client−side HTML scripting in Microsoft's Internet Explorer web browser. VBScript still requires a
'host', however, and we're going to learn about these hosts in this book.

Is VBScript a 'Real' Programming Language?
Professional software developers who are masters of full−blown, stand−alone, compiled languages such as
C++, Visual Basic, and Delphi often look down their noses at VBScript, and at scripting languages in general.
'Scripting is not real programming,' they'll say. This point of view is understandable, and in a sense correct,
since a scripting language generally does not provide the kind of flexibility, control, power, and speed that a
'real' programming language does. However, this point of view fails to account for the fact that a scripting
language like VBScript exists in order to solve a different set of problems. Microsoft did not create VBScript
to compete with languages such as VB and C++, but rather to supplement them, to solve problems that they
are either not capable of handling, or for which they would be overkill.
In many ways, a canoe cannot compare to a much larger, more powerful, and faster speed boat. Speed boats
have comfortable seats, are much less susceptible to tipping over, have powerful engines, can tow water
skiers, and are ideal for large, treacherous bodies of water that would swallow a canoe in a matter of minutes.
A canoe, however, can go through narrow channels and shallow water that a larger boat never could, is much
more nimble, can easily navigate through rocky whitewater rapids, and, if it hits a dry spot, can easily be
picked up and carried to the water on the other side. Different tools are better for different problems.
VBScript is a worthy, and in some cases crucial, addition to any developers toolbox. Haven't you ever seen a
speed boat towing a canoe behind it?

Other Languages, Other Platforms
As you've surely guessed by now, VBScript is not alone in the world of scripting languages. It's not even
alone in the smaller world of scripting languages produced by Microsoft. Microsoft also produces and fully
supports JScript, which can be used just about anywhere that VBScript can be used. Before VBScript version
10


What Can You Do With VBScript?
5, JScript provided more features than VBScript. Awhile back, Microsoft pledged to keep VBScript on a par

with JScript when it comes to features and capabilities. They will always remain separate languages, with
different syntax and different ways of accomplishing the same thing, but Microsoft's goal is to make the
choice of which Microsoft scripting language to use a matter of preference, not necessity.
JScript is closer in the nature of its syntax to C, and therefore C and C++ programmers might be more
comfortable using JScript. JScript is also compatible with the ECMAScript standard. ECMAScript is a
web−scripting standard that was developed by the European Computer Manufacturers Association (ECMA).
The intent of ECMAScript is to provide a standard cross−platform scripting language, especially in the
context of web scripting. The latest versions of Netscape's JavaScript and Microsoft's JScript are ECMAScript
compatible, and in fact, both of these languages were used in the creation of the ECMAScript standard. You
can download a description of the ECMAScript standard (ECMA−262) from
/>VBScript is not ECMAScript compatible, and therefore cannot generally be used in non−Microsoft operating
systems (such as the many UNIX variants) or non−Microsoft web browsers (such as Netscape Navigator or
Opera Software's Opera). That said, third party companies have developed tools that enable VBScript support
in Netscape Navigator and in non−Windows operating systems. For example, NCompass Labs produces
scriptactive, which is a 'plug−in' for Netscape Navigator that allows that browser to host VBScript code and
ActiveX controls, which are not natively supported. You can reach NCompass Labs at
/>On the Active Server Pages front (see Chapter 14), two companies offer products that allow you to develop
VBScript ASP applications on several non−Windows platforms. The most well−known of these is Chili!Soft
( which produces Chili!Soft ASP. According to the Chili!Soft marketing literature
'Chili!Soft ASP provides full ASP support for Web servers from Apache, Lotus, Netscape, O'Reilly and
Microsoft, running on Windows NT, Sun Solaris and IBM AIX, with other Web servers and Operating
Systems coming soon.' Another player in this market is Halcyon Software ( />which produces Instant ASP. According to the Halcyon marketing literature 'Halcyon's Instant ASP (iASP)
provides Microsoft−compatible Active Server Pages (ASP) functionality and capability on all Web server,
application server, and operating system platforms − from NT to Sun, Novell, AIX, AS/400, S/390, Apple,
OS/2 and Linux to Apache, Netscape, Websphere, and more.'

What Can You Do With VBScript?
VBScript by itself is a powerful language, but you really can't do anything with it without a host. A host is an
application that allows scripts written in VBScript to run within its context. Since VBScript cannot be
compiled like a normal application and run on its own, it must have a host to read the script and compile it.

This section contains a high level discussion of the many different ways you can use VBScript, and you'll find
that these different capabilities are intrinsically tied to a particular host. Each of these subjects will be
discussed in detail throughout the book.

The Windows Script Host
This Windows Script Host (WSH formerly known as the Windows Scripting Host) is a scripting host that
allows you to run scripts within the Windows operating system. This idea is very similar to UNIX Shell
scripting and DOS batch files. These scripts can be run from the command line (in a DOS command shell
window) or within native Windows. WSH is ideal for automating common tasks, writing network login
scripts, and administering an NT network. Besides just executing the scripts you write, the WSH also includes
and installs a set of objects that make it easy to access the Windows file system and environment. WSH
11


What Can You Do With VBScript?
scripts are not limited to those written in VBScript. It can execute scripts written in any language that
conforms to the ActiveX Scripting specification, including JScript, Perl, and Python.
After covering the details of the VBScript language, this book will cover the Windows Script Host. The WSH
is a great way to try out many of the sample scripts and code snippets that appear throughout the book.
However, many of these examples will be dependent on a certain host. For instance, in order to try out some
Active Server Pages scripts, you'll need to install Microsoft's Internet Information Server or Personal Web
Server.
We will cover the Windows Script Host in Chapter 10.

Windows Script Components
A Windows Script Component (WSC) is a COM component that is written in a combination of script code
and XML. They can be used on the server to execute business logic, read and write to databases, and even
participate in Microsoft Transaction Server (MTS) transactions. You can even define events in a WSC. This
is all functionality that was previously only available to C++, Visual Basic, and Delphi programmers, and is
an exciting development.

In Chapters 5 and 6, you'll learn how, from VBScript, to use COM components and objects that are available
from Microsoft and other companies. In Chapter 8 you'll learn how to create classes in VBScript. Then, in
Chapter 9, we'll show how to group together one or more VBScript−based classes together into a Windows
Script Component. Since a WSC is just like any other COM component, you can even use them from other
COM−enabled languages such as Visual Basic and Delphi.

Client−Side Web Scripting
Client−side web scripting is something you probably encounter every day, and may not even know it. Even
the simplest HTML pages on the web today often contain script code. Client−side web scripts are downloaded
into the browser along with the HTML code that defines the layout of the web page. In fact, these scripts are
embedded in (and are a part of) the HTML code.
Client−side web scripting is a fairly large subject, with many books dedicated to it, and we're going to cover
as much of it as we can in this book. In Chapter 11, we'll talk about what we call 'general' client−side web
scripting. This includes simple things like adding dynamic effects with MouseOver events, as well as
validating and submitting forms to a web server. We use the term 'general' only because this type of scripting
has been around awhile and become commonplace. Web browsers from Microsoft and Netscape going several
versions back support general web scripting.
In Chapter 12, we'll introduce you to what we call 'high−powered' client side scripting. This includes subjects
such as Dynamic HTML (DHMTL), Behaviors, and HTML Components (HTCs). These are powerful
techniques and tools with which you can build rich web−based user interfaces that, besides looking great, help
maximize server resources and network bandwidth. We'll also discuss the trade−offs of using VBScript and
Microsoft's high−powered client−side scripting options, since these technologies are only supported by the
latest versions of Microsoft's Internet Explorer (IE) web browser. (The IE−only limitation used to be a major
drawback for someone considering writing a DHTML application, but HTML Applications now open up a
whole world of possibilities for script authors.)

12


What Can You Do With VBScript?


Server−Side Web Scripting
Server−side web scripting is accomplished with Microsoft's Internet Information Server (IIS) and Active
Server Pages (ASP). Internet Information Server is the sophisticated web server that Microsoft ships with the
Windows NT Option Pack, a free add−on for licensed users of Windows NT Version 4. Active Server Pages
are essentially HTML pages with embedded script code. ASPs can include client−side web scripts that will be
downloaded to the browser with the rest of the HTML, but also include scripts that are executed only in the
web server. These embedded server−side scripts are executed before the page is released by the web server to
be downloaded to the client's web browser. Using ASP scripts, you can dynamically change the content of the
page as it is being built. For instance, you could store a user's profile and preferences in a database, and use
these preferences to customize the content and appearance of the web page whenever the user requests it.
Don't dismay, though, if you are not lucky enough to have a dedicated NT Server with Internet Information
Server installed on it. For no cost, you can download Microsoft's Personal Web Server (PWS), which runs on
Windows 95 and Windows 98. Using Personal Web Server, you can develop your own Active Server Pages,
and open them in any web browser. We'll cover ASP in Chapter 14.

Client−Server Web Scripting (Remote Scripting)
Remote Scripting is a cool new technology from Microsoft that allows you to treat ASP pages as if they were
COM objects. From the client, you can 'call' the scripts embedded in an ASP page that's sitting on the server.
This is important, because it means you can keep complicated, lengthy, and/or proprietary business logic on
the server it won't be downloaded to the browser, but client−side scripts in the browser can execute it as if it
were. This also means less round trips to the server to reload entire pages. We'll discuss Remote Scripting in
Chapter 12.

HTML Applications
An HTML Application (HTA) is one of the most exciting script−related technologies to come from Microsoft
yet. Introduced with Internet Explorer Version 5, an HTML Application is a web page that runs in its own
window outside of the browser. The implications of this are significant. You can now use VBScript, HTML,
DHTML, Cascading Style Sheets (CSS), HTML Components, Windows Script Components, and all the rest
to build stand−alone graphical applications that do not require a web server or even a web or network

connection to run. Also, since HTAs run outside the browser, they are considered 'trusted,' which means they
are free of the security restrictions imposed by the browser. We predict that you will soon start seeing HTAs
everywhere.
As Internet Explorer 5 becomes as ubiquitous as previous versions of Internet Explorer have become, script
authors everywhere will be able to build and distribute non−web−dependent HTML Applications to users.
This should be especially popular with the Windows Script Host authors who have previously been limited to
lightweight popup dialog boxes for communicating with users. We'll cover HTAs in detail in Chapter 13.

Talking to Databases
Updating and reading information to and from databases is one of the most common needs of any developer,
regardless of language or platform. Certainly, most applications written for business use depend on databases.
VBScript developers are definitely not left out in the cold here. Microsoft's Active Data Objects (ADO)
provide VBScript authors with full access to just about any data storage mechanism available, including
relational databases (such as Access, SQL Server, and Oracle), object databases, flat files, and e−mail and
groupware repositories. In Chapter 15, we'll introduce you to ADO and show you the basics of reading from
13


What Can You Do With VBScript?
and updating database tables, calling stored procedures, and more.

Adding Scripting to your Windows Applications
Adding scripting and 'macro' capability to a Windows application written in C++, Visual Basic, Delphi, and
other languages used to be a complicated, often home−grown affair no more. Using the free Microsoft Script
Control, Windows developers can now extend their applications by adding support for VBScript, JScript,
Perl, and other ActiveX−enabled scripting languages. Applications can expose objects to the scripting engine
and allow end users and field implementers to customize the application, all with just a few extra lines of
code. We'll show you how in Chapter 16.

What Tools Do You Need to Use VBScript?

In it's simplest form, all you need to create and run simple VBScript programs is a plain text editor (such as
Windows Notepad) and the Windows Script Host. However, each of the many scripting hosts and components
that we'll cover in this book require that you install certain applications and components on your PC or
network. In order to keep you from having to jump all around the book to figure out what needs to be
installed, each chapter will start with a section called What Tools Do You Need?
That said, one of the first questions most people ask is 'What editor should I use?' This is a matter of personal
preference, and part of the decision hinges on whether or not you want to spend any money on an editor.
There are commercial and shareware products available that provide sophisticated features that are especially
useful for script developers. These features include color−coded syntax highlighting, automatic indenting,
automatic backups, branch collapsing, super−charged clipboards, and macros. Some people prefer to use the
simplest Windows text editor of them all, Notepad, which is usually installed automatically with Windows.
We do not endorse any particular editor (and this book will not use any examples that require you to use a
certain editor), but here is a list of some 'free' and commercial products that you might want to consider. Most
of the products have time or functionality limited demos that you can try for free. This is by no means a
complete list (there are dozens of text editors on the market), and you might want to explore the Internet for
more options. If you decide to use a shareware editor, we encourage you to register it and purchase a license.
These products are often a 'labor of love' for a programmer just like you, and registrations help keep the
product alive:
• PC Editor Freeware Kazu Soft
• Programmer's File Editor Freeware Alan Phillips
/>• Edit Pad 'Postcardware' JGSoft −
• GNU Emacs for Windows Open Source (freeware) GNU
/>• Codewhiz Shareware Incatec
• TextPad Shareware − Helios Software Solutions
• UltraEdit−32 Shareware IDM Computer Services
• Codewright Commercial Premia Corporation
• HomeSite Commercial Allaire
• Multi−Edit Commercial American Cybernetics
• PrimalScript Commercial Sapien Technologies
Web scripters can also use two well−known products from Microsoft: Visual Interdev and FrontPage.

14


What's New in VBScript 5?

What's New in VBScript 5?
VBScript version 5 contains some significant new language features that should be most welcome to users of
previous versions of VBScript. For the record, the last version of VBScript to receive general distribution was
VBScript 3.1. Most people upgrading to version 5 will be coming from version 3.1. Version 4 of VBScript
was distributed with Microsoft Visual Studio version 6, but did not contain any new language features. The
changes between version 3.1 and 4 all had to do with IntelliSense and debugging features in Visual InterDev
version 6.
If you're new to VBScript and not familiar with what we're talking about here don't worry, we'll cover all of
this later in the book.

Regular Expressions
VBScript now supports regular expressions through a new intrinsic VBScript object: RegExp. VBScript 5
developers can instantiate a RegExp object and use it to evaluate string data against a pattern, which is a kind
of shorthand description of how a string of data might look. For example, the pattern "\w+\@[.\w]+" checks to
see if a string looks like an e−mail address. Regular expression patterns are obviously rather strange looking,
and can take some getting used to. However, regular expressions are a powerful way to check the validity of
data (for instance, to see if your user entered a properly formatted e−mail address), or to search for all kinds of
strings in text files or other text−based data.
The pattern syntax in the VBScript RegExp object is exactly the same as in JScript, which is in turn based on
Perl regular expressions. JScript has supported regular expressions for a while, and adding this powerful
feature to VBScript is Microsoft's fulfillment of a promise to keep VBScript and JScript 'in synch'
feature−for−feature. We'll cover the RegExp object in Chapter 7.

Classes
The ability to define a class natively in VBScript is a welcome addition to VBScript 5. Classes are a great way

to organize you code for readability, maintainability, and reusability. A class is a self−contained unit of code
that acts as a template for an object. Classes are the building blocks of components.
Since scripts are generally self−contained units (with all of the code that makes up a script embedded in a
single text file), and since, in languages such as VB and C++, classes are defined in their own separate text
files, the VBScript development team had a bit of a challenge to give VBScript developers the ability to
define a class. They solved the problem with the Class statement, which allows you to define a class within a
script. You define the properties and methods (public and private) for a class between Class and End Class
statements. You can then instantiate this class into an object variable and use it just like any other object.
Writing classes is very straightforward. If you've had any experience writing classes in Visual Basic, you
won't have any trouble. We'll show you the ins and outs of VBScript classes in Chapter 8.

With Statement
Visual Basic developers know how much coding time and processing time the With statement can save, but
VBScript developers have, until now, been unable to take advantage of this great feature. The With statement
is a shorthand, code blocking statement. Between With <<object name>> and End With statements, you don't
have to repeat the name of an object every time you refer to one of its properties and methods. This saves you
typing, and saves the compiler and runtime engine from having to resolve the reference to that object every
time your code refers to it and that makes your script run faster. Here's a quick example (we'll cover the With
15


What's New in VBScript 5?
statement in Chapters 5 and 6):
Instead of typing this:
oCustomer.Name = "Mary Smith"
oCustomer.Address = "1234 Some Street"
oCustomer.ZipCode = "12345"
oCustomer.Update

You can type this:

With oCustomer
.Name = "Mary Smith"
.Address = "1234 Some Street"
.ZipCode = "12345"
.Update
End With

Eval, Execute, and ExecuteGlobal
These three new VBScript functions are included in version 5 to create compatibility with the JScript Eval
method. They each do about the same thing, but which one you use depends on the scope of what it is your
trying to do. The idea is to provide a way to evaluate and execute code 'on the fly' at runtime. For instance,
your user could type in x = (2 + 2) * 8, which you would then send to the Eval function. Eval would tell you
that this formula results in the number 32.
Execute and ExecuteGlobal are for executing blocks of script code on the fly, whereas Eval is for executing
single expressions such as the example we just used. Deciding whether to use Execute or ExecuteGlobal
depends on the namespace that the script code you're executing needs to have access to, but we're not going
to get into that here. We'll discuss these three new functions in Appendix A.

Function Pointers
The new GetRef function allows you to 'bind' a script procedure to any available object event in a DHTML
page. Previously, this had to be accomplished through the ObjectName_EventName syntax or through an
HTML tag. When the event occurs, the procedure name passed to the GetRef function will be executed. For
example:
Set Window.OnLoad = GetRef("MyFunction")

When the Window.OnLoad event fires, MyFunction will be executed. We'll cover the GetRef function in
Appendix A.

DCOM Support
Distributed COM (or DCOM) allows you to create and communicate with objects that live on another

computer. Then, that computer's memory and processor handle the load of running that object. This is known
as 'distributed processing'. Once a distributed object has been instantiated in your script, your code has no idea
(nor does it care) that the object lives on another computer somewhere on your network. Microsoft added
DCOM support to VBScript 5 by adding an additional optional argument to the CreateObject function. You
pass the name of the computer on which the object is registered as the second argument to the CreateObject
function. For example:
16


Code Conventions
Set oCustomer = CreateObject("MyComponent.Customer", \\MyRemoteServer)

Code Conventions
We have used a number of different styles of text and layout in the book to help differentiate between the
different kinds of information. Here are examples of the styles we use, and an explanation of what they mean:
Advice, hints, and background information comes in this type of font.
Important

Important pieces of information come in boxes like
this.
Important words are in a bold type font.
Words that appear on the screen in menus, like File or Window, are in a similar font to the one that you see on
the screen.
Keys that you press on the keyboard, like Ctrl and Enter, are in italics.
Code comes in a number of different styles. If it's something we're talking about in the text when we're
discussing the MsgBox, for example it's in a fixed−width font. If it's a block of code from a program, then it's
also in a gray box:
Dim varTest
varTest = "Hello There"
MsgBox TypeName(varTest)


Sometimes you'll see code in a mixture of styles like this:
Sub window_onload()
On Error Resume Next
x = 3/0
Msgbox x
End Sub

The code with a white background is something that we've already looked at and don't wish to examine
further.
These formats are designed to make sure that you know exactly what you're looking at. We hope that they
make life easier.

Tell Us What You Think
We've worked hard on this book to make it enjoyable and useful. Our best reward would be to hear from you
that you liked it and that it was worth the money you paid for it. We've done our best to try to understand and
match your expectations.
Please let us know what you think about it. Tell us what you liked best and what we could have done better. If
you think this is just a marketing gimmick, then test us out drop us a line! We'll answer, and we'll take
whatever you say on board for future editions. The easiest way is to use e−mail:
You can also find more details about Wrox Press on our web site. There you'll find the code from our latest
17


Customer Support
books, sneak previews of forthcoming titles, and information about the authors and the editors. You can order
Wrox titles directly from the site, or find out where your nearest local bookstore with Wrox titles is located.
The address of out site is:



Customer Support
If you find a mistake in the book, your first port of call should be the errata page on our web site. If you can't
find an answer there, send an e−mail to telling us about the problem. We'll do everything
we can to answer promptly. Please remember to let us know the book your query relates to, and if possible the
page number as well. This will help us to get a reply to you more quickly.

18


Chapter 1: A (Very) Short Introduction to
Programming
Overview
In trying to squeeze the basics of writing computer programs into one chapter, we may be attempting the
impossible, but we're going to do our best. The reason for including this chapter is that many people come to a
scripting language, like VBScript, as their first language. Perhaps you're a network systems expert who wants
to use VBScript and the Windows Script Host to write login scripts and automate administration tasks. Or
perhaps you're a web designer who feels the need to branch out from the visual aspects of creating web pages
and into writing scripts to drive content. Or perhaps you're just a person who wants to learn a programming
language for the fun of it. Either way, you've come to the right place.
Programming or "writing code," as some people like to call it is a huge subject. Many volumes have been
written about it. During this chapter, in a single paragraph, we might introduce multiple unfamiliar concepts.
We're going to move pretty fast, but if you read along closely and try out the examples, you'll probably be just
fine.
Keep in mind that even an in−depth discussion of how to write computer programs might not even begin to
touch on subjects such as architecture, systems design, database design, testing, documentation, and all the
rest of the subjects that an accomplished software developer must master. But don't let all that discourage you.
Everyone starts somewhere, and this is a great place for you to start learning the art and science of making a
computer sing. Consider this chapter a brief introduction to the important building blocks. It won't make you
an expert overnight, but hopefully it will give you a the know−how you'll need in order to get the most out of
the rest of the book.


Variables and Data Types
In this section, we're going to be moving quickly through some of the most basic concepts of programming:
variables, comments, using built−in VBScript functions, and other syntax issues.
The first concept we're going to touch on is that of variables. Simply put, a variable is a place in memory
where your script holds a piece (or a set) of information (we'll use the term data in place of "information"
throughout most of this discussion). The data stored in a variable might be very simple, like the number
10,000, or very complex, such as a whole series of numbers, ranging from 1 to 10,000.
Behind the scenes, a variable is a reserved section of the computer's memory. Just to make sure we're clear,
memory is temporary working space for the computer. Memory is transient that is, things that are placed in
memory are not stored there permanently. That's what the hard drive is for. Since memory is transient, and
since variables are stored in the computer's memory, variables are by extension transient as well. Your script
will use variables to temporarily store a piece of information that the script needs to keep track of. (If your
script needs to store that information permanently, it would store it in a file on the hard disk, or in a database,
which is also stored permanently on the hard drive.)
In order to make it easier for the computer to keep track of all the millions of pieces of information that might
be stored in memory at any given moment, memory is broken up into chunks. Each chunk is exactly the same
size, and each chunk is given an address. You don't need to worry about memory addresses, but it's useful to
know that a variable is a reserved set of one or more chunks. Different types of variables take up different
19


×