|  | Click Here!

Search the site:
EXPERT SEARCH

| Programming Languages
| Databases
| Security
| Web Services
| Network Services
| Middleware
| Components
| Operating Systems
| User Interfaces
| Groupware & Collaboration
| Content Management
| Productivity Applications
| Hardware
| Fun & Games

EarthWeb sites
Crossnodes
Datamation
Developer.com
DICE
EarthWeb.com
EarthWeb Direct
ERP Hub
Gamelan
GoCertify.com
HTMLGoodies
Intranet Journal
IT Knowledge
IT Library
JavaGoodies
JARS
JavaScripts.com
open source IT
RoadCoders
Y2K Info

# Chapter 2

# The VBScript Language

by Brian Johnson

CONTENTS

- Introduction
- Differences Between Visual Basic and VBScript
- Programming in VBScript
  - Creating a Test Page
  - What a Program Is
  - Concepts You Should Understand: Variables and Procedures
  - The Anatomy of VBScript Code
- Data Types
  - Subtypes of Variant Types
  - Using Variables
  - Constants
- Program Flow
  - Operators
  - Decision-Making in Programs
  - `If...Then...Else`
  - `For...Next`
  - `Do...Loop`
  - `For Each...Next`
  - `While...Wend`
- Review

## Introduction

VBScript is a member of Microsoft's Visual Basic family of development products. Other members include Visual Basic (Professional and Standard Editions) and Visual Basic for Applications, which is the scripting language for Microsoft Excel. VBScript is a scripting language for HTML pages on the World Wide Web and corporate intranets.

In this chapter, you'll learn about

- The differences between Visual Basic and VBScript
- The syntax of the VBScript language
- Program flow in VBScript
- Interaction between the program and the user in VBScript

## Differences Between Visual Basic and VBScript

If you know Visual Basic, you'll probably not have any trouble at all with VBScript. The parts of the language we cover in this chapter are basically the same in Visual Basic, with a few subtle differences. Let's talk briefly about these differences and what you should be aware of as you read this chapter.

One of the things you should be interested in is the safety and security of client machines that access your Web site. Microsoft took this consideration into account when creating VBScript. Potentially dangerous operations that can be done in Visual Basic have been removed from VBScript, including the capability to access dynamic link libraries directly and to access the file system on the client machine.

These security precautions are important because access to the client machine's operating system and internal processes could be disastrous. Of course, people run software that they download from the Internet every day. For some reason, though, people who simply use the Internet, as opposed to those of us who create it, are leery of active content. For that reason, there is a special feature of active controls for the Internet-a digital signature.

A digital signature is a file or piece of code that verifies the authenticity of a program or file. Two distinct things must happen in a secure transaction such as this: The client must be sure of where the active control is coming from and that it hasn't been tampered with along the way.

## Programming in VBScript

This section of the chapter doesn't assume that you know anything about programming in Visual Basic. If you're well versed in the language, you can use this section as a review. If you haven't programmed before at all, you'll get the introduction that you need.

To start, we'll create a template that you can use to test various concepts in VBScript. We'll then talk about the things that make up a program and what you need to understand in order to create active HTML pages.

### Creating a Test Page

Many new programmers learn how to program by writing small programs that run from the command line. In HTML, there is no command line, so we'll set up a skeleton page that we can use to test some of the concepts and functions covered in this book. We'll call the skeleton program `tester.htm`. Listing 2.1 contains the code that makes up the skeleton program.

> Listing 2.1. `tester.htm`.

>     <HTML>

>     <HEAD>

>     <TITLE>Tester Page</TITLE>

>     </HEAD>

>     <BODY>

>     <H1>Tester Page for VBS</H1>

>     <HR COLOR="BLUE">

>     <INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Click to test the code">

>     <SCRIPT LANGUAGE="VBS">

>     <!--

>     Sub Btn1_OnClick()

>     End Sub

>     -->

>     </SCRIPT>

>     </BODY></HTML>

In most VBScript programs, you'll need to attach the initialization of a program to some sort of action. In the `tester.htm` page, use the button click event to trigger the action that takes place. To be able to see what happens, we need to change the property of a control on the page, or we can use a message box. Once we have the skeleton program in place, we can test code in the browser.

To start, we'll create a Hello World program. Hello World is a traditional program created in various forms to test input and output techniques. The first Hello World program is fairly simple. To create the script, the following code is added to the `Btn1_OnClick` event in `tester.htm`:

>     Sub Btn1_OnClick

>     Dim Message

>     Message="Hello World!"

>     MsgBox Message, 0,"Tester Result"

>     End Sub

To test the new code, save `tester.htm` and then open it in Explorer 3.0. You'll see the result when you click the button, as shown in Figure 2.1.

Figure 2.1 : Tester program with message.

The great thing about having a program like `tester.htm` available is that you can test any small piece of code you want. By saving the file to your desktop, you can easily open the file in Notepad and Internet Explorer 3.0 at the same time, as shown in Figure 2.2. You can then edit and save the file and see the results immediately.

Figure 2.2 : Notepad and Internet Explorer working together.

Let's take a look at what's happening in `tester.htm`. The browser reads in the file just as with any HTML document. Notice that the button we've created on the page is no different from the buttons that we create for forms. Microsoft did this so that the same objects created for forms could easily be used for interaction with scripts. This method also helps HTML designers who are used to working with forms.

So, the `<H1>` text shows in the browser, followed by a horizontal rule and finally our button. The browser now hits the `<SCRIPT="VBS">` tag. Here the browser hands off to the scripting engine, which in turn hands off to the VBScript interpreter. The VBS code is then parsed by VBS, compiled on the fly, and run. Our result shows up in the form of the message box.

If some of this isn't quite clear to you now, it should be by the end of the chapter.

### What a Program Is

At this point, it might be a good idea to discuss what constitutes a program. Thinking about what's going on with the machine will help you later when you're trying to come up with applications for VBScript in your Web pages.

A computer program is a set of mathematical instructions that perform a task. To make it easier for programmers to get computers to do things, languages have been developed to allow programmers to write instructions for the computer in terms that humans can deal with.

Many computer languages exist. They can be broken into two broad categories: low level and high level. Low-level languages deal directly with what's going on inside the computer, whereas high-level languages keep the programmer thinking at a different level. Low-level languages get closer to the chip. Assembler is an example of a low-level language. When you write a program in Assembler, you do the same sorts of things that you do in a language such as Visual Basic, except that you are much more precise with the chip. Assembler tends to be a little cryptic to people just getting to know it:

>     MOV     BX,0001H

>     LEA     DX,Msg

>     MOV     CX,My_Msg

>     MOV     AH,40H

>     INT     21H

Writing programs in a high-level language such as Visual Basic is much more like writing instructions in plain English. The conceptual buffer between a language that is close to the chip and a higher-level language is called abstraction. You know more about what's going on when you read an assembly language program, but you could do it in Basic and not have to worry about moving blocks of memory around yourself.

We can add a layer of abstraction to Visual Basic itself. To teach programming concepts, some instructors use a tool called pseudo code. Pseudo code is simply an instruction translated into plain English. I don't use pseudo code much, but I'll cover it briefly here so that you're familiar with the concept.

If you translated the code in Listing 2.1 into pseudo code, it would look like the code shown in Listing 2.2.

> Listing 2.2. `tester.htm` translated into pseudo code.

>     Create a button on the page called Btn1

>     This is the start of a script in the VBS language

>     This comment hides the code from browsers that can't understand it.

>     When the user clicks the button:

>     Create a space in memory called Message

>     Set the value of Message to "Hello World"

>     Create a dialog box containing the value of Message

>     End the routine

>     End of the comment

>     End of our script

I won't use this method much in this book because it essentially makes you read the same program twice. I mention it, though, because it shows how you should be thinking when you read through code listings.

When you think about a computer language being mathematical, you don't really need to worry that there are big concepts that you need to understand before you begin to program. To think about what a computer needs to do to process information, think of the game 20 Questions. In 20 Questions, one person has the magic word. Everyone else is allowed to ask 20 questions with a "Yes" or "No" answer. The person who knows the magic word decides whether the question deserves a "Yes" or a "No."

If the magic word is "cow," and the question is, "Is it an animal?", the answer would be "Yes." This is about the level on which the computer works. It remembers things, it compares things, and it can tell you whether two things are the same. Languages such as Visual Basic add features that can work on the things that the machine stores in memory. Programmers are the people asking the questions. The better the question, the more likely it is that you'll get to the ultimate answer.

### Concepts You Should Understand: Variables and Procedures

You should understand some simple concepts before you begin to program. Among these concepts are variables and procedures.

A variable is a value stored in memory. If you wanted to get technical, you could say that variable is a name that represents an address containing information stored in memory. For our purposes, thinking of a variable as being equal to a value is fine.

A program is made up of one or more procedures. A procedure is an instruction block in VBScript. Regular procedures, or `Sub`s, simply act on data, but a special procedure called a `Function` returns a value to the procedure that called it. Be aware that all your scripts will be made up of procedures and `Function` blocks.

You know that your VBScript programs will begin with a `<SCRIPT>` tag and end with a `</Script>` tag. Your procedures and `Functions` will work the same way. The procedure is created and it is ended. Your program code goes in between.

### The Anatomy of VBScript Code

Let's take a look once again at our `tester.htm` file. The script section of the page has a definite structure as shown in Figure 2.3.

Figure 2.3 : A VBScript code block is broken down.

The first thing you'll notice in the VBScript code block is the `<SCRIPT LANGUAGE="VBS">` line. Keep in mind that you must close out your script code block with a `</SCRIPT>` tag. If you don't add this tag, your script usually won't run and you won't know what's going on because you aren't going to see any error messages. Errors like this are tough to track down because if your code block is large, you might start hacking away at perfectly good code to see if you can figure out what's wrong. An error like this can waste a lot of time because nothing you try works.

TIP
If your script isn't running and you're not getting error messages from your browser, check your HTML.

The next tag that you should get used to adding to a script block is the comment tag. You won't run into a problem with most browsers if you don't add this tag, but it's a good idea to get used to adding it anyway. If nothing else, this tag helps you to see your scripting blocks more easily in your HTML documents. Like the `<script>` tag, the comment tag should have a closing tag, although not having a closing tag will not affect your script in a browser that recognizes the `<SCRIPT>` tag.

Procedures make up most of the rest of a script code block. They have opening and closing lines and are accessible from one another. The first procedure run in a script depends on what events take place within the HTML page. An event is usually an action taken by a user, such as clicking on a button, but other events can also be triggered within an HTML page. Other possible events include timer events, mouse movement, and messages sent from controls.

To review, an HTML script is enclosed by the `<SCRIPT>` `</SCRIPT>` tag pair. The `LANGUAGE="VBS"` attribute sets the scripting language to VBScript. The VBScript script code should be written inside a comment tag, `<!-- -->`. Procedures are blocks of code within the script that make up the program.

## Data Types

As mentioned, a variable is a name that represents the contents of some space in memory. Thinking of a variable in terms of memory space will help you to understand an important concept in programming: data types.

All variables in VBScript are of the type variant. A variant is a variable that is simply the name for a piece of data. The variant type doesn't differentiate between types of data until the time comes to process that data. This means that a variable can represent literally any value or type of value. We'll talk more about this ahead.

### Subtypes of Variant Types

The variant type has a number of subtypes. Let's go through each of the subtypes and discuss how a variable of any given subtype will take up space in memory.

#### Boolean

One of the most basic data types in programming is the Boolean data type. This subtype in VBScript can have a value of either `true` or `false`. The Boolean type takes up very little space in memory.

#### Byte

The byte subtype can be a whole, positive number in the range of 0 to 255. Like the Boolean subtype, the byte subtype takes up very little space in memory.

#### Integer

The integer subtype takes up 2 bytes in memory and can be an integer value in the range of -32,768 to 32,767. An extra byte of storage makes a big difference in the value that a variable can hold.

#### Long

The long variable subtype is 4 bytes in size and can be a whole number in the range of -2,147,483,648 to 2,147,483,647.

#### Single

The single subtype contains a single-precision, floating-point number. Precision refers to the number of bytes of fractional value storage allotted to the variable. A single-precision number allots 2 bytes for fractional value storage. It takes 4 bytes to store a variable of the subtype single. The range of values that a single can hold is -3.402823E38 to -1.401298E-45 for negative values and 1.401298E-45 to 3.402823E38 for positive values.

#### Double

The double subtype takes up 8 bytes of storage, 4 bytes of which are reserved for a fractional value. The double subtype is extremely precise and is usually reserved for advanced mathematical and scientific operations. It has a range of -1.79769313486232E308 to -4.94065645841247E-324 for negative values and 4.94065645841247E-324 to 1.7976931348632E308 for positive values.

#### String

The string subtype is a group of up to approximately 2 billion characters. The size of the string variable depends on the length of the string.

#### Date

The date subtype is a number that represents a date in the range of January 1, 100 to December 31, 9999.

#### Empty

The empty subtype is returned for variants that aren't initialized. If the variable is a number, the value is `0`. If it's a string, the value is `""`.

#### Object

The object subtype contains the name of an OLE Automation object. The object can then be manipulated using the variable.

#### Error

The error subtype contains an error number. You can use the generated error number to generate an expanded explanation of the error.

### Using Variables

Now that you know what variables are all about, let's take a look at how they are used in your VBS scripts.

#### Declaring Your Variables

Strictly speaking, you don't need to declare your variables in VBScript. You could simply set the variables that you need on the fly:

>     MyString="This is my string"

One of problems with setting the value of variables without first declaring them is that the variables become difficult to track. For example, you set the value of a variable somewhere in code, but you can't remember where the variable started. In addition to just being good programming practice, declaring your variables will make it easier for you to read and maintain your code.

To declare a variable in a VBS script, you use the `Dim` statement. Dim stands for dimension:

>     <SCRIPT LANGUAGE="VBS">

>     <!--

>          Option Explicit

>          Dim MyString

>          MyString="This is my string"

>     -->

>     </SCRIPT>

Notice that in addition to declaring our variable with the `Dim` statement, we added the `Option Explicit` statement to the beginning of the code. Adding `Option Explicit` will require you to declare all variables in your script. Using this statement is completely up to you. If you use `Option Explicit` but don't declare a variable, your script will generate an error when run.

You can declare more than one variable at a time. Just use the `Dim` statement and put a comma between every new variable name:

>     <SCRIPT LANGUAGE="VBS">

>     <!--

>          Dim Name, Address, City, State, Zip

>     -->

>     </SCRIPT>

#### Assignment

To assign a value to a variable, place the variable on the left followed by an equals sign and the value on the right:

>     Name="Brian Johnson"

Remember that variables in VBScript are variants. VBScript determines the nature of the variable when you run the script. There are really only two types of data: strings and numbers. String data is always held in quotation marks.

#### Scope

The scope of a variable refers to where in the script the variable is available for processing. A variable declared inside a procedure is limited in scope to that procedure. If a variable is declared outside of the procedures in the script, it is available to all the procedures in the script. Listing 2.3 illustrates the scope of variables in VBS scripts.

> Listing 2.3. Scope of variables in VBS scripts.

>     <HTML>

>     <HEAD>

>     <TITLE>VBS Variable Scope</TITLE>

>     </HEAD>

>     <BODY>

>     <H1>Tester Page for VBS</H1>

>     <HR COLOR="BLUE">

>     <INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Local Variable">

>     <INPUT TYPE="SUBMIT" NAME="Btn2" VALUE="Script Wide Variable">

>     <INPUT TYPE="SUBMIT" NAME="BTN3" VALUE="Out of Scope">

>     <SCRIPT LANGUAGE="VBS>

>     Option Explicit

>     Dim MyGlobal

>     MyGlobal="Access Ok"

>     Sub Btn1_OnClick()

>     Dim MyLocal

>     MyLocal="Local access Ok!"

>     MsgBox MyLocal,0,"Btn1 Clicked"

>     End Sub

>     Sub Btn2_OnClick

>     MsgBox MyGlobal,0,"Btn2 Clicked"

>     End Sub

>     Sub Btn3_OnClick

>     MsgBox MyLocal,0,"Btn3 Clicked"

>     End Sub

>     -->

>     </SCRIPT>

>     </BODY>

>     </HTML>

If you run the code, you'll see that you can access the local variable by clicking Btn1. If you click Btn2, you'll access the variable that we declared globally. Finally, if you click Btn3, you'll get an error (see Figure 2.4) because the `Btn3_OnClick` procedure tries to access the variable declared in the `Btn1_OnClick` procedure.

Figure 2.4 : An out-of-scope variable generates an error.

When discussing the scope of a variable, you'll often hear the term lifetime. Lifetime refers to the amount of time that the variable exists in memory. At the procedure level, the lifetime of the variable is as long as it takes to run through the procedure. At the script level, the variable is live for as long as the script is live. You can extend the lifetime of a procedure-level variable by declaring the variable as static. A static variable will retain its value between calls to the procedure. To declare a variable as static, simply use the `Static` keyword:

>     Static MyVariable

#### Scalar

The types of variables we have talked about so far have been scalar variables. A scalar variable has only one value assigned to it at a time. Depending on the types of programs you write, you'll probably use scalar variables often in your scripts. When modeling the world, though, you often need to work with sets of values. To work with these values, you need to use a different type of variable known as an array.

#### Array

An array is like a list. When you go to the grocery store, you often carry a list of the items that you need to purchase. If you were to assign the list to a scalar value, it might look something like this:

>     MyList = "peas, carrots, corn"

Although it's easy enough to have `MyList` contain the contents of the list, it's not very easy to figure out which item is which. That's where an array comes in. An array lets you easily specify items in the list and retrieve those items individually. Let's take a look at a simple array.

You declare an array variable in VBScript the same way you do a scalar variable. The difference is that you specify the number of items in the array:

>     Dim MyList(4)

Arrays in VBScript start their count at zero, so an array is declared with the highest count number in the array. In this case, `MyList` has a total of five items.

Looking at Listing 2.4, you can see that we've drawn five buttons on the page. An array variable, `MyList`, is declared with five items, and each item is assigned a different value. In the click event for each button, we attach the value of an array item to a local scalar variable called `Item`. We then call a procedure named `ShowMessage`, passing `Item` as a parameter. The `ShowMessage` procedure takes the value of `Item` and plugs it into the `MsgBox` function, which brings up the message box containing the value of the particular array item.

> Listing 2.4. Shopping list of items.

>     <HTML>

>     <HEAD>

>     <TITLE>Tester Page</TITLE>

>     </HEAD>

>     <BODY>

>     <H1>Tester Page for VBScript</H1>

>     <HR COLOR="BLUE">

>     <INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Item 1"><BR>

>     <INPUT TYPE="SUBMIT" NAME="Btn2" VALUE="Item 2"><BR>

>     <INPUT TYPE="SUBMIT" NAME="Btn3" VALUE="Item 3"><BR>

>     <INPUT TYPE="SUBMIT" NAME="Btn4" VALUE="Item 4"><BR>

>     <INPUT TYPE="SUBMIT" NAME="Btn5" VALUE="Item 5"><BR>

>     <SCRIPT LANGUAGE="VBScript">

>     <!--

>     Option Explicit

>     Dim MyList(4)

>     MyList(0)="Corn"

>     MyList(1)="Carrots"

>     MyList(2)="Peas"

>     MyList(3)="Chicken"

>     MyList(4)="Cake"

>     Sub Btn1_OnClick

>      Dim Item

>      Item=MyList(0)

>      ShowMessage(Item)

>     End Sub

>     Sub Btn2_OnClick

>      Dim Item

>      Item=MyList(1)

>      ShowMessage(Item)

>     End Sub

>     Sub Btn3_OnClick

>      Dim Item

>      Item=MyList(2)

>      ShowMessage(Item)

>     End Sub

>     Sub Btn4_OnClick

>      Dim Item

>      Item=MyList(3)

>      ShowMessage(Item)

>     End Sub

>     Sub Btn5_OnClick

>      Dim Item

>      Item=MyList(4)

>      ShowMessage(Item)

>     End Sub

>     Sub ShowMessage(SelItem)

>     MsgBox SelItem,0,"Item picked"

>     End Sub

>     -->

>     </SCRIPT>

>     </BODY>

>     </HTML>

You can also create multidimensional arrays. A 2-D array is declared like this:

>     Dim MyArray(4,9)

This declaration creates a table containing five rows and 10 columns. You can pull a particular value from the array using `MyArray(row,column)`. The upper limit for multidimensional arrays is 60 dimensions.

One final note on arrays: You can declare what are called dynamic arrays that change sizes as the script is run. To declare a dynamic array, use the `Dim` or `ReDim` statement without adding a size value to the array name:

>     Dim MyDynamicArray()

To use this array, you would `ReDim` the array, adding a size value to the name:

>     ReDim MyDynamicArray(14)

You can `ReDim` an array as many times as needed.

#### Naming Conventions

The names that you give variables in VBScript are the same as for any other named item in a script. Variable names must begin with an alphabetical character:

>     '  This is Ok

>     Dim MyVariable

>     ' This is not Ok

>     Dim @Variable

In addition, variables cannot contain embedded periods and are limited to 255 characters. Finally, you cannot use the same name for two different values in the same scope. It's okay to have the same variable name declared in many different procedures, but the same variable name cannot be declared globally, and it cannot be declared twice in the same procedure.

When you declare variables, you should consider a few naming conventions. Table 2.1 lists these conventions.

Table 2.1. Naming conventions in VBScript.

Variable Subtype | Prefix
Boolean | `bln`
Byte | `byt`
Date | `dtm`
Double | `dbl`
Error | `err`
Integer | `int`
Long | `lng`
Object | `obj`
Single | `sng`
String | `str`

To use these naming conventions properly, you need to know the probable data subtype of the variables you declare. To name a variable that you know will contain a string, use the prefix along with a descriptive name for the variable:

>     Dim strName

The same rules follow for values that you know will be of a specified subtype:

>     Dim dblMiles

>     Dim blnEmpty

>     Dim intTotal

Using a convention such as this can save you time in the long run. It's much easier to see that you're about to make a mistake when you see an equation like `strValue + dblMiles` than if you simply saw `Value + Miles`.

The scope of a variable also has a naming convention. If you have a script-level variable, you can add an `s` to the prefix:

>     Dim sdblMyNumericValue

We'll talk more about coding conventions throughout the book. As new conventions are introduced, they will be incorporated into the sample code.

### Constants

A constant is a named value that doesn't change throughout a script. For example, the value of the speed of light through room-temperature air at sea level is about 760 miles per hour. To use this constant in a script, you simply declare it, assign it, and use it like a variable. To differentiate a value that you want to be a constant in your script, you should use your own naming conventions, so that you don't try to reassign the value of the constant that you've created.

>     'vbSOL Speed of Light

>     Dim vbSol

>     vbSol = 760

Once you set the value of the constant, you can use it in your script as if it were the actual number. Keep in mind though that constants in VBScript are essentially just variables that you don't change in your program. Unlike other languages that allow you to set the value of a constant to `static`, there's no way to make a variable in VBScript unchangeable.

## Program Flow

Program flow has to do with how your program moves from one line or procedure to another. To illustrate the flow of a program, many programmers use a flowchart.

The specifics of program flow have mostly to do with decision-making in scripts. Next, we'll talk about decision-making steps in VBScript and how different conditional and looping statements affect your script.

### Operators

Before we can talk about how flow control works in a program, you need to be familiar with the operators used in the logic operations that control flow. Most of these will be familiar to you if you have a rudimentary background in math. Others might not be quite as obvious.

Table 2.2 contains the operators you can use in VBScript programs.

Table 2.2. VBScript operators.

Operator | Purpose
`+` | Addition
`And` | Logical And
`&` | Concantation operator
`/` | Division
`Eqv` | Logical Equivalence
`^` | Exponential
`Imp` | Logical Implication
`\` | Integer Division
`Is` | Logical Is (Refer to same object)
`Mod` | Modulus Operator (Remainder)
`*` | Multiplication
`-` | Negation and Subtraction
`Not` | Logical Not
`Or` | Logical Or
`Xor` | Logical Xor

You'll be using some of the logic operators in the next sections. The mathematical operators are used for math operations and, in some cases, concatenation. For example:

>     MyString = "Now is the time" & " for all good men..."

is functionally equivalent to

>     MyString = "Now is the time" + " for all good men..."

### Decision-Making in Programs

Decision-making in programs is what programming is all about. Keep in mind that computers aren't really that good at thinking things through. You have to tell the program what to do every step of the way. Humans use a method of thinking that has what are known as fuzzy logic characteristics. If you were to ask more than one person to name the color of a particular scarf, you might get the answers red, pink, orange, and scarlet. If you ask a computer to name the color of an element on the screen, you'll get back the exact color name. Taking it one step further, if you ask the same group of people if the scarf is red, they all might answer "Yes." If you ask a computer if the screen element is red, it will return a `yes` value only if the item is exactly red.

Always keep in mind the limitations of the machine. Write good questions and you'll get good answers.

### `If...Then...Else`

The `If...Then...Else` statement is one of the basic capabilities of a computer language. This statement tests for the truth of a statement and, depending on the answer, processes information or moves on to another piece of code. Let's look at an example of an `If...Then...Else` statement in a program (see Listing 2.5) and then talk about what's happening in the code.

> Listing 2.5. `If...Then...Else` in a VBS script.

>     <HTML>

>     <HEAD>

>     <TITLE>Tester Page</TITLE>

>     </HEAD>

>     <BODY>

>     <H1>Tester Page for VBScript</H1>

>     <HR COLOR="BLUE">

>     <CENTER>

>     <FONT COLOR=RED SIZE=5>Question:</FONT><BR>

>     <FONT COLOR=BLUE SIZE=6>Who is buried in Grant's tomb?</FONT><BR>

>     <INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Click to test the code">

>     <INPUT TYPE="TEXT" NAME="Txt1">

>     </CENTER>

>     <SCRIPT LANGUAGE="VBSCRIPT">

>     <!--

>     Sub Btn1_OnClick()

>     Dim Message

>     If Txt1.Value = "Grant" then

>     Message="You're right!"

>     Else

>     Message="Try again"

>     End If

>     MsgBox Message, 0,"Tester Result"

>     End Sub

>     -->

>     </SCRIPT>

>     </BODY></HTML>

The example in Listing 2.5 is simple yet powerful. First of all, it's our first useful program. We answer a question, and the computer tells us if we are right or wrong. Immediate feedback and interaction are what it's all about. Let's break down the `Btn1_OnClick` procedure to see what's happening up close.

When Btn1 is clicked, the `If...Then...Else` statement asks if the value of the Txt1 text input box is `Grant`. If the answer to that question is true, the program sets the value of the variable `Message` to `You're right`. (See Figure 2.5.) If the answer is false, the value of `Message` is set to `Try again`. Notice that there is absolutely no room for error when answering this question. If the user enters `grant`, `GRANT`, or `US Grant`, the program will skip to the `Else` part of the program, and the message will be "Try again." Later you'll learn how to make `If...Then...Else` statements a little more tolerant.

Figure 2.5 : Outcome of a quiz answer.

If you have a simple `If...Then` statement, the statement can be just a single line:

>     If x=4 then y=12

When the statement takes more than one line, you need to close it off with an `End If` statement.

### `For...Next`

The `For...Next` statement is used to run a block of code statements a certain number of times:

>     Dim x

>     For x = 1 to 10

>     Edit1.Value = x

>     Next

In this example, the counter starts at 1 and repeats `Edit1.Value = x` 10 times. You can also specify the way that the value of x is counted, using the `Step` keyword. You can use an `If...Then` statement to exit the loop, if necessary:

>     Dim x

>     For x = 5 To 50 Step 5

>     Edit1.Value=x

>     If x > 20 Then Exit For

>     Next

In this case, the counter starts at 5 and stops at 50 for a total of 10 iterations. The loop is exited after five iterations, because x is greater than 20.

You could also use the `Step` value to count down, using negative numbers. Starting with a higher number and counting down to a lower one would look something like this:

>     Dim x

>     For x = 10 to 1 Step -1

>     Edit1.Value = x

>     Next

### `Do...Loop`

Another common looping statement is `Do...Loop`. A `Do...Loop` statement is usually better to use than a `For...Next` and `Exit For` combination. The `Do...Loop` statement allows you to create a loop that runs an infinite number of times. You need to be careful when using this statement-you don't want to accidentally get your script into a loop that it can't get out of:

>     Dim x

>     x=1

>     Do Until x = 25

>     x = x + 1

>     Loop

In this example, the place where you need to be careful is in `Do Until x = 25`. If the initial value of x was 30, the code would loop continuously without the `x = 25` value ever being met.

There are two ways to test for a `true` value in the `Do...Loop` statement. You can use the `Until` keyword to repeat the loop until a condition is true or the `While` keyword to repeat while the condition is true:

>     Dim x

>     x = 10

>     Do While x < 100

>     x = x + 10

>     Loop

By placing the `While` or `Until` keyword after the `Loop` statement, you can make sure that the code inside the loop is run at least once:

>     Dim x

>     x = 1

>     Do

>     x = x + 1

>     If x > 30 Then Exit Loop

>     Loop Until x = 30

The code in this `Do...Loop` block is run at least once before it's ended. We've also added a safety feature in the form of an `Exit Loop` command that's issued if x is found to be greater than 30. If x is greater than 30, there is no chance that the value will ever be 30.

### `For Each...Next`

The `For Each...Next` loop is used like the `For...Next` loop. It is used to test conditions in collections of objects. Objects have properties that are specified by keywords that are appended to the object name after a period. If I had an object with the property of `color`, you could access that property with `MyObject.Color`. Groups of objects are called collections, and you can test each of the objects for the truth of a statement using `For Each...Next`:

>     For Each Car in Lot

>          if Car.Color = "Red" then

>          MsgBox "Red car!", 0, "Answer"

>          End If

>     Next

In this example, the collection of objects is called `Lot`, and the objects are of the type `Car`. We go through the cars in the lot, and when we get to a red one we see a message. You'll learn more about objects in Part II of this book.

### `While...Wend`

According to Microsoft, `While...Wend` is included in VBScript for those programmers who are familiar with its usage, but it's not well documented. Microsoft recommends using `Do...Loop` instead, but let's take a quick look at the `While...Wend` statement to become familiar with its usage:

>     Dim x

>     x = 1

>     While x < 10

>     x = x + 1

>     Wend

The `While...Wend` statement repeats until the value of the `While` portion of the statement is `true`.

## Review

In this chapter, we talked about the differences between Visual Basic and VBScript. You learned that a script is a set of instructions that control the behavior of objects in your Web pages. You learned about data types and that all variables in VBScript are variants. Finally, you learned about program flow and the statements used to loop through a program.

| Use of this site is subject certain Terms & Conditions. Copyright (c) 1996-1999 EarthWeb, Inc.. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Please read our privacy policy for details.