Skip to main content.

Web Based Programming Tutorials

Homepage | Forum - Join the forum to discuss anything related to programming! | Programming Resources

Web Programming Unleashed

Chapter 22 -- The VBScript Language

Chapter 22

The VBScript Language

by Keith Brophy and Tim Koets


In this chapter, you will learn the fundamentals of programming with VBScript. You will first learn the basics, such as creating variables, using operators, controlling the flow of code, and creating procedures. Then you will see how to use existing HTML and ActiveX controls along with VBScript to enhance your Web pages. You will also learn about Script Object Model Objects and other objects you can use along with VBScript to take advantage of the cutting-edge Internet technology on the Web.

All About Variables

Before you learn the more advanced aspects of VBScript programming, you need to become familiar with the basics. The first thing you need to know about VBScript programming is how to create a variable.

Creating Variables

When you create a variable, you have to give it a name. That way, when you need to find out what's contained inside the variable, you use its name to let the computer know to which variable you are referring. In most cases, the name you assign to the variable helps you recall what the variable is used for. For example, a variable named Age is much easier to remember and understand than a variable named X.

You can be quite creative when you name variables in VBScript, but you can't use just any name you want; you have to follow a few naming rules. The first rule is that the name must begin with a letter. A variable name of 1ToMany, for example, is not allowed. Second, the variable name cannot contain a period or space. A variable named Customer Name is illegal and produces an error. You can't use a period either because VBScript uses periods to reference properties of objects. Third, the length of a variable name cannot exceed 255 characters. You should keep your variables short but meaningful or expect your fingers to get very sore.

After you've decided on a name for your variable, you have two ways to create it. The first way, called the explicit method, is where you use the Dim keyword to tell VBScript you are about to create a variable. You then follow this keyword with the name of the variable. For example, if you want to create a variable called Quantity, you would enter

Dim Quantity

and the variable will then exist. It's that simple! If you want to create more than one variable, you can put several on the same line and separate them by commas, such as

Dim X, Y, Z

The second way to create a variable is called the implicit method. In this case, you don't need to use the Dim statement. You can just start using the variable in your code, and VBScript creates it automatically. If, for example, you want to store the quantity of an item, you can simply enter

Quantity = 10

using the implicit method. You don't have to create the variable explicitly with a Dim statement.

If you take no special steps, you can freely intermix the implicit and explicit methods of declaring variables. When you want to, you can choose to set aside a named storage space before you use it by giving it a name in advance through the Dim statement. On the other hand, you can also rely on the fact that when you refer to something by name in a statement and space hasn't yet been reserved for storing that variable, it will be created for you on-the-fly.

This method of intermixing implicit and explicit declarations can produce programs that are confusing to follow, to say the least. Fortunately, VBScript gives you a way to force a consistent explicit declaration approach. To make the explicit method a requirement and prevent the implicit allocation of names, you must place the command

Option Explicit

in the first line of the first script in your HTML document, as shown in the following segment:



Option Explicit

[the rest of your script code]



At the time of this writing, VBScript was still in beta form, as was Internet Explorer 3.0. With the beta software, the Option Explicit statement was not yet fully implemented and had to be placed in the first line next to the HTML comment tag to be included without errors. The beta implementation of Option Explicit did not always explicitly force variable declaration as specified.
I expect that Option Explicit will be fully implemented in the final release of Internet Explorer 3.0. You might find further updates on implementation status by visiting Microsoft's Web site at, the Macmillan Publishing site at (look for the book title under, or the authors' update site at In the samples in the book, the Option Explicit statement appears next to the comment tag to prevent errors

The Option Explicit statement therefore makes explicit declarations a requirement, and you have to define every variable with a declaration such as Dim. With Option Explicit, if you have not defined the variable before you use it, you can't use it! Therefore, you need to enter the command

Dim Quantity

before you enter

Quantity = 10

In the explicit method, if you assign Quantity with a value of 10 before creating it, you will get an error.

You might be wondering, "Why use the explicit method when I can just start using variables?" The implicit method is certainly more convenient while you are writing the code-that is, until you spell a variable wrong. What will happen? VBScript will go ahead and create another variable based on your misspelling, and you will get the wrong result. Consider, for example, the following code segment:



Quantity = 2

Quantity = Quantity + 3



You would expect the result to be 5, right? And it would be. Suppose you misspelled Quantity in the second line of code:



Quantity = 2

Quantity = Quantite + 3



The variable Quantite would be created on the fly, and because it was never defined or previously assigned a value, it would be assigned a value of zero. The result variable Quantity, then, would wind up being 3, not 5. If, on the other hand, you were using the explicit method of creating variables, you would enter the code as


<!--  Option Explicit

Quantity = 2

Quantity = Quantity + 3



which would give you a runtime error if you spelled Quantity wrong because you had not declared it first. The runtime error that results from using Option Explicit typically alerts you to the problem and leads you to correct the error right away. On the other hand, if you didn't use Option Explicit and therefore didn't receive the runtime error, you have a much more subtle problem. You might not even notice the incorrect result, and even if you did, you would probably have a more difficult time targeting the source of the problem.

The Contents of Variables

VBScript is a new product, but it is a language derived from its parent product, Microsoft Visual Basic. VBScript is essentially a subset of Visual Basic. When you create variables in Visual Basic, you have the opportunity to specify what type of data you want to store in a variable. If, for example, you want to store integers in a variable, you can declare the variable as an integer variable using the integer data type. As a result, if you try to store anything other than an integer in the variable, Visual Basic either converts the data automatically into integer format or tells you the assignment cannot be made.

If you can be specific about the type of data you are storing, your code has the potential to be less error-prone because you make fewer mistakes when assigning data to variables. On the other hand, programming is easier if you do not have to worry about restricting a variable to specific types of data. Visual Basic also gives you the choice of creating variables when the kind of data you want to store doesn't matter. This special type of variable is called a variant.

A variant is a special type of variable that can store a wide variety of data types. In many programming languages, variables can contain only a specific predeclared type of information, such as integers or strings. However, you can assign an integer value to a variant in one statement and then replace that integer with a string value in a subsequent statement. Variables in VBScript are based on the variant

VBScript uses the variant as the basis for variables you create. The variant is used most often to store numbers and strings, but it can store a variety of other types of data. These data types are often called subtypes because the variant can represent them all internally. VBScript keeps track of these subtypes on its own; you usually just store whatever you want in the variable. VBScript matches the data to the best subtype and behaves accordingly.

To understand what the variant actually is, you should understand all the other data types that the variant can represent. These data types are taken from VBScript's parent, Visual Basic. By learning about these data types, you will begin to see how the variant works and what you can and cannot store in a VBScript variable. Here is a list of all the subtypes that the variant uses to represent the data you store in a variable:

When you are considering how data is stored in a variable, think of a closet full of shoe boxes. Every type of shoe has a certain type of box that can store the shoe. In addition to the boxes that store specific types of shoes, other larger, generic-looking boxes are on hand. These generic boxes can store any of the types of shoes. The shoe boxes that store specific types of shoes represent the subtypes, whereas the boxes that can store any kind of shoe represent the variant. The variant is a "fit-all" data type that can hold any of the subtypes.

The following paragraphs explain what type of data can be stored in VBScript variables.


You can set the Boolean data type to either True or False, which VBScript represents as -1 and 0, respectively. This subtype is useful when you want to determine or set a condition for the variable.


The byte data type can store an integer value between 0 and 255. It is used to preserve binary data and store simple data that doesn't need to exceed this range.


The integer data type is a number that cannot contain a decimal point. Integers can range from -32,768 to +32,767.


Variables of the long data type are also integers, but they have a much higher range, -2,147,483,648 to 2,147,683,647, to be exact. Because this data type is also an integer, you cannot use decimal points. Long integers are also quite common and are usually used when the range of the number exceeds the smaller range of the integer.


The single subtype represents floating-point, or decimal, values, which means that numbers represented by this subtype include decimal points. The range jumps to a whopping -1.4E - 45 to -3.4E 38 for negative numbers and 1.4E - 45 to 3.4E 38 for positive numbers. (These numbers are expressed in scientific notation.)

Scientific notation is a way to represent very small or very large numbers. A number is expressed as x.xxEyyy where x.xx is a number and yyy represents how many places to shift the decimal point over in the number. If yyy is positive, the decimal moves to the right. If yyy is negative, the decimal moves to the left. Thus, the expression 3.45E02 becomes 345 and 2.34E-03 becomes 0.00234


Double is another floating-point data type, but this data type has an even larger range than the single data type. The range for the double is -4.9E -324 to -1.8E 308 for negative numbers and 4.9E -324 to 1.8E 308 for positive numbers.

Date (Time)

The date subtype stores dates and times in a special format. This popular subtype places the date in a predefined format that other functions in VBScript can act upon. If, for example, you have a date variable named HireDate and you want to know what year is in the date, you can simply use the function Year(HireDate) to find it. If you use the date subtype to represent HireDate, the function can retrieve the year from the variable.


The string is used to store alphanumeric data-that is, numbers, letters, and symbols. The string is another commonly used subtype for VBScript variables.


The object data type is a special subtype used to reference OLE automation objects within a VBScript application or another application. Microsoft created OLE automation to enable one application to share information and control with another.


The error subtype is used for error handling and debugging purposes.


The empty subtype is used for variables that have been created but not yet assigned any data. Numeric variables are assigned 0, and string variables are assigned "" in this uninitialized condition.


The null subtype refers to variables that have been set to contain no data. Unlike the empty subtype, the programmer must specifically set a variable to null.

How Variables Are Stored

In many languages, you can allocate a variable to accept a specific type of data-say, integer data. As stated earlier, you cannot directly create a variable in VBScript that "knows" ahead of time it will contain only integer data. Instead, you can create a variable that can take on integer values along with any of the other subtypes listed previously. VBScript handles the conversions automatically. Suppose, for example, that you declare a variable in VBScript as

Dim Item

Then, suppose that you set the variable Item equal to an integer value:

Item = 23

VBScript stores the value 23 in the Item variable as an integer. If, on the other hand, you were to set Item with a string, as

Item = "Tacoma, Washington"

the text you place in the variable Item gets stored internally as a string. The great advantage of the variant is that you don't have to worry about placing the wrong type of data in a variable. In Visual Basic 4.0, for example, you can declare an integer value with the statement

Dim Distance as Integer

You could enter a distance in miles easily by using the statement

Distance = 6

Suppose, however, that you want to enter a distance of 6.5 miles. If you enter the statement

Distance = 6.5

Visual Basic 4.0 will store the distance as 7. This happens because you told Visual Basic the variable was based on the integer data type, which cannot store decimal points. As a result, Visual Basic 4.0 obediently stores it as an integer by rounding the value, in this case, up to an even seven miles. This problem is automatically solved for you in VBScript, where you simply enter the declaration

Dim Distance

and then set the distance using

Distance = 6.5


Distance = 6

or even

Distance = "6 Miles"

It doesn't really matter what you set the Distance variable to. Because the variant data type is used, VBScript automatically converts the data into the best possible subtype internally. The first assignment is converted into a single-precision value, the second to an integer, and the third to a string. As you can see, the variant gives you complete flexibility in entering data because you aren't limited by predeclared data types. Furthermore, the variant can automatically convert data from one type to another. If, for example, you have two variables assigned as

Distance = 6.75

Units = " feet"

you can put the two variables together into a third variable using

Result = Distance & Units

which makes Result equal to the string 6.75 feet. Now suppose you were using Visual Basic 4.0. If you defined the Distance variable as the single data type and you defined Units as a string, the command

Results = Distance & Units

would result in a Type Mismatch error. This error simply means that Visual Basic 4.0 isn't able to add a string to a number. It can add strings to strings and numbers to numbers, but not strings to numbers. Visual Basic 4.0 doesn't automatically add a string to a number because the two are incompatible. When using variants, however, VBScript makes some assumptions for you. On its own, it determines that when you're adding a number to a string, you're going to get a string result. Because the variant can take on any of the data types, it simply stores the result in the variable as a string result.


Sometimes in writing code, you will want to refer to values that never change. The values for True and False, for example, are always -1 and 0, respectively. Values that never change usually have some special meaning, such as defining True and False. These special kinds of values that never change are called constants. The constants True and False are sometimes referred to as implicit constants because you do not need to do anything to reference their constant names. They are immediately available in any script you write.

You have already seen the True and False constants in action in the previous code samples. Keep in mind that changing the value of either of these intrinsic constants is illegal. Therefore, the statement

False = 10

would result in an error because VBScript has already defined False to be 0. VBScript won't let you change a constant, even though you can change a variable.

Unfortunately, you cannot create true constants with VBScript because the language will still enable you to change the value of any constant variable you define. Many languages have special ways to declare a constant so that you cannot alter its value anywhere in the program. VBScript does not offer this level of strict enforcement. However, you can simulate a true constant by following two rules:

As an example, if you want to create a constant that contains your company name so you can use it throughout your code, you can use the following statements to define the constant:


COMPANY = "Acme Enterprises"

Then use the variable throughout your code, never assigning the variable COMPANY to any other value. This convention will help you work with and recognize simulated constants.

The Scope and Lifetime of a Variable

When a variable is created, you can either use it within a specific procedure or share it among all the procedures in the script. A variable's availability within its environment is referred to as the scope of a variable. Variables in VBScript can have two kinds of scope. When a variable is declared inside a procedure, it has local scope and can be referenced only while that procedure is executed. Local-scope variables are often called procedure-level variables because they exist only in procedures. When you declare a variable in a procedure, it automatically has local scope, which means that only the code within that procedure can access or change the value of that variable. However, you might want to share a variable with other procedures. If you declare a variable outside of a procedure, it automatically has script-level scope and is available to all the procedures in your script.

Scope refers to where within a script a given variable is available based on the declaration, such as locally within a procedure or globally across the script

Another characteristic of variables is that they exist for different amounts of time, depending on their scope. This property of a variable is often referred to as its lifetime. Script-level variables are created outside of any procedures using the Dim keyword, and they exist from the time the variable is declared until the time the script is finished running.

The lifetime of a script-level variable is equal to the entire life of the Web page. On the other hand, when you declare a procedure-level variable using Dim, the variable exists only while the procedure is run. Once the procedure ends, the variable is destroyed.


You create arrays using the same keyword you use to create variables-the Dim keyword. An array created with the Dim keyword exists as long as the procedure does and is destroyed once the procedure ends. If you create the array in the main script, outside of the procedure, the values will persist as long as the page is loaded. You can create two types of arrays using VBScript: fixed arrays and dynamic arrays. Fixed arrays have a specific number of elements in them, whereas dynamic arrays can vary in the number of elements depending on how many are stored in the array. Both types of arrays are useful, and both have advantages and disadvantages.

Fixed-Length Arrays

You can create fixed-length arrays using the following syntax:

Dim Array_Name(count - 1)

where Array_Name is the name of the array and count is an integer value representing the number of containers you want the array to contain. The statement

Dim Names(19)

creates an array called Names that consists of 20 containers, often called elements. You can store 20 different names in this array of data called Names. Consider the shoe box analogy discussed earlier in this chapter. Creating an array is like having 20 shoe boxes, all the same size, in which you can store shoes. Instead of naming each box separately, you can give them all the same name and refer to them using an index, such as ShoeBox(1), ShoeBox(2), Shoebox(3), and so on.

The index of the array always starts at zero and ends at count -1. In the case of the Names array, the number of containers, or elements, in the array ranges from Names(0) to Names(19) for a total of 20 elements. To see how this works, look at the following code:

Dim Names(19)

Dim i

For i = 0 to 19

    Names(i) = "Unknown"


This simple code listing sets every element of the Names array equal to the string "Unknown". This process is similar to putting the same type of shoe in every shoe box in your closet. This code listing uses a loop to set each element. Essentially, the program treats the variable i like a counter and keeps incrementing it by 1 all the way from 0 to 19. The Names(i) = "Unknown" code statement is executed 20 times, and each time the i value is different. You need to remember that the first container in your array has an index of 0, not 1. In this example, the first element in the array is Names(0), not Names(1). If you forget this rule and start with Names(1), you'll only be able to use 19 of the containers, not 20.

Dynamic Arrays

The second type of array you can create is the dynamic array. The benefit of a dynamic array is that if you don't know how large the array will be when you write the code, you can create code that sets or changes the size while the VBScript code is running. A dynamic array is created in the same way as a fixed array, but you don't put any bounds in the declaration. As a result, your statement becomes

Dim Names()

Eventually, you need to tell VBScript how many elements the array will contain. You can do this with the ReDim function. ReDim tells VBScript to redimension the array to however many elements you specify. ReDim takes dimensions the same way Dim can. The syntax is

ReDim Array_Name(Count - 1)

So, if you enter

ReDim Names(9)

you will create an array that has room to store 10 elements. This way, you can set the size of the array while the code is running, rather than when you write the code.

Suppose that you dimension an array in your code, and later on, you need to increase the size of the array. No problem, right? You just use ReDim again and increase the number of elements in the array. That method will certainly work, but the entire array will be erased in the process. This situation is like adding more shoe boxes to your closet by taking out all the shoe boxes, emptying them, and putting the total number you want back in empty. Do not despair; VBScript contains a special keyword called Preserve that comes to the rescue.

The Preserve keyword is very important when using ReDim. Suppose, for example, that you create a dynamic array, specify its storage space by using ReDim, fill it with data, and then later decide to make it larger so you can fill it with more information without losing your original data.

If you want to erase whatever is in the array when you resize it, leave off the Preserve keyword. If you want to keep what you have, make sure to include Preserve when you ReDim an array.

Concepts such as determining the size of an array, creating multidimensional arrays, and erasing the contents of arrays are discussed in Teach Yourself VBScript in 21 Days by Brophy and Koets from

Using Operators

Now that you've seen how to create variables, you need to know how to use operators to make those variables do useful work for you. Operators are given that name because they operate on the variables associated with them. As you begin to write VBScript code, you will use operators so much that their use will become natural to you. In this section, you will learn about each VBScript operator, as well as how to use them.

Arithmetic Operators

The first major class of operators is arithmetic operators. Arithmetic operators enable you to perform simple arithmetic on one or more variables.

Arithmetic operators are a special class of operators specifically intended to perform arithmetic on the corresponding data

You will be familiar with most of these operators because you have been exposed to them in everyday life. Few people will be surprised to find, for example, that the + operator performs addition. Some operators, however, might be new to you. In any case, you need to understand how to apply these operators to variables and literals in VBScript code.

Addition (+)

The first arithmetic operator is the addition operator. As you surely guessed, the addition operator is used to add values, whether they are stored in variables, constants, or literal numbers. You also use the + operator to concatenate strings, but for now, just focus on its capability to add numbers-I'll discuss string concatenation later in this chapter.

Subtraction (-)

The subtraction operator should also be very familiar to you. This operator works the same way the addition operator does except that it subtracts one or more numbers. Otherwise, the syntax is the same.

Multiplication (*)

Addition and subtraction are important, but you also need a way to multiply values together. Most computer languages use the * symbol to indicate multiplication, not the ´ symbol. You might be able to use ´ on paper, but to the computer, ´ is a variable, not a multiplication symbol. If you enter the command

Result = 3 x 2

the interpreter will give you a syntax error. To be correct, you should enter the command

Result = 3 * 2

Division (/ and \)

The division operator is the last of the four commonly used arithmetic operators, and division is the most complicated arithmetic operation a computer performs. This statement shouldn't surprise you if you remember learning long division in grade school math class. VBScript has two types of division operators. The first operator handles numbers with decimal points. Usually referred to as the floating-point division operator, it's represented by the / symbol in code listings. If you are relatively new to programming, you might be wondering at this point if you can use a more familiar symbol for the same purpose. The answer is no; you cannot use the familiar Ö symbol in computer speak-you must instead use the / symbol for floating-point division. The floating-point division operator is designed to divide values with decimal points, but it can also divide numbers without decimals. The syntax for division is the same as for any of the other operators presented so far:

c = a / b

This code divides the variable b into a and puts the result into the variable c. Similarly, you could use numbers and perform a division such as

c = a / 2

which, in this case, divides the variable a in half. If the variable a were set to some valid numeric value, say 3, the result stored in c would be 1.5.

From time to time, you might want to divide integer values or perform a division without a decimal point in the result. In that case, you want to use integer division. Integer division is performed the same way floating-point division is, but the operator is different. Rather than use a forward-slash (/), you use a backward slash (\).

Using the same numbers as before, if you were to enter

c = a \ 2

an integer division would take place. The decimal would be chopped off, and the result would be 2 rather than 1.5. You need to remember that integer division turns your result into an integer by rounding the original values of the operands to integers to calculate the results. For example, consider the result of the following calculation:

c = 4 \ 1.9

The value of variable c after this statement executes will be 2. VBScript processes this calculation after an internal rounding of the operands. The expression VBScript will act upon in this case is not c = 4 \ 1.9 or c = 4 \ 1. Instead, it rounds the operands to perform the calculation of c = 4 \ 2, which equals 2.

Additional operators such as the exponent, the modulo, and negation operators are discussed in Teach Yourself VBScript in 21 Days from

Comparison Operators

The first set of operators VBScript provides are arithmetic operators. This section discusses the second type: comparison operators. As the name implies, you use comparison operators to compare one or more variables, numbers, constants, or a combination of the three. VBScript has many different types of comparison operators, and each type checks for a different comparison condition.

Equality (=)

You use the equality operator to see if a variable, constant, or number is equal to another. It's common to mistake the equality operator for the assignment operator, which is also represented by an equals sign. You use the assignment operator to set a variable equal to another variable, number, string, constant, or other data entity. For example, the statement

a = b

assigns the value contained in b to the variable a.

The equality operator, on the other hand, is used to test whether one value is equal to another. The syntax for the equality operator looks similar to that for the assignment operator

a = b

where a and b can be variables, constants, or numbers. The context in which you use the expression determines whether it is treated as an assignment or an equality check. Equality is always used in the context of checking a condition. For example, a statement such as

if a = b then

is an example of the equality operator because it is a conditional check. As a rule of thumb, you can assume that if a = b appears in a statement by itself, it is an assignment statement. If you see a = b as part of any other expression, it is used in the equality context.

Inequality (<>)

Another important comparison operator is the inequality operator. You use this operator to test whether a variable is not equal to another variable or some data element. The syntax for the inequality operator is

a <> b

where a and b are variables, constants, strings, or numbers. Again, the expression returns True if the condition is indeed true and False if it isn't. For example, you can take the following code

If TravelTime = 0 Then

    MsgBox "The speed cannot be calculated because the time is zero.

  Please enter a valid time."


    Speed = Distance / TravelTime

    txtSpeed.Value = Speed

End If

and make the following change-that is, use the inequality operator rather than the equality operator-and get the same results:

If TravelTime <> 0 Then

    Speed = Distance / TravelTime

    txtSpeed.Value = Speed


    MsgBox "The speed cannot be calculated because the time is zero.

  Please enter a valid time."

End If

Using the inequality operator is sometimes more convenient and sensible than using the equality operator.

Greater Than and Less Than (> and <)

You might have a condition where you don't care whether a variable is equal to another, but you do want to know whether it is greater than or less than another variable, number, or constant. In such a case, you need the greater-than and less-than operators. The syntax for these two operators is

a > b


a < b

where a and b are variables, constants, numbers, or strings, and the result is True if the expression is true. Otherwise, the expression returns False. For an example of its use, consider the following code:

If TravelTime > 0 Then

    Speed = Distance / TravelTime

    txtSpeed.Value = Speed

Else If TravelTime < 0 Then

    MsgBox "You cannot enter a negative value for the time!"

Else If TravelTime = 0 Then

    MsgBox "The time must be greater than zero!"

End If

Here, you see the greater-than, less-than, and equality operators all in use. If the variable TravelTime is greater than zero, a speed can be calculated, but if TravelTime is less than zero or equal to zero, the user must be notified-any such value would not be valid.

You could write the same code in another way if you think carefully about the conditions being satisfied. If a travel time is not greater than zero and not less than zero, you know it must be zero. Even without checking for this value, you can tell that zero is the only possibility left! You could therefore rewrite the code as

If TravelTime > 0 Then

    Speed = Distance / TravelTime

    txtSpeed.Value = Speed

Else If TravelTime < 0 Then

    MsgBox "You cannot enter a negative value for the time!"


    MsgBox "The time must be greater than zero!"

End If

This code works just as well as the previous code. The first method was used to emphasize the purpose of the equality expression. The first method is also a better approach in some respects; for example, the purpose of each branch of the code is more clearly defined and easier to read and debug when the conditions are explicitly named. Code that is clearer is usually also easier to maintain and less subject to bugs.

The less-than-or-equal-to and greater-than-or-equal-to (<= and >= ) operators are discussed in Teach Yourself VBScript in 21 Days from

Object Equivalence (Is)

The last comparison operator is designed for objects, which are discussed in more detail later in the chapter. For now, consider an object such as a command button that you can place on a Web page. The syntax of the Is operator is

result = object_reference1 Is object_reference2

where object_reference1 and object_reference2 are references to objects and result is either True or False, depending on whether the statement is true.

This operator does not compare one object to another, nor does it compare values. This special operator simply checks to see if the two object references in the expression are the same object. Suppose, for example, you have a command button in your script that you have defined as TestButton. You have another variable, myObject, that is set to reference different objects at different points in your program. Assume a statement has been carried out that assigns the variable myObject to reference TestButton, such as

Set myObject = TestButton

If the script later carries out the expression

result = myObject Is TestButton

it will return the True in the variable result because TestButton is indeed the same object as that referred to by myObject. If, on the other hand, you were to enter

result = myObject Is SomeOtherTestButton

result would be False because the two objects are not the same.

As you can see from this discussion, you must apply some special rules when you deal with objects. For example, you must use the Set statement to assign an object's value, as shown previously. You cannot directly compare two objects with an equal statement, such as

if myObject = TestButton  ' illegal syntax

Logical Operators

The last category of operators in VBScript is logical operators. The logical operators are probably the most difficult operators to understand.

Negation (Not)

The first operator is called the negation operator. This operator has the following syntax:

result = Not expression

Table 22.1 shows the result variable in relation to expression.

Table 22.1. Negation (Not) results.

If expression is...
Then result is...

If you enter the expression

a = Not 1 > 2

where the expression is 1 > 2, the result is stored in the variable a. The value stored in variable a will be True. The expression 1 > 2 is false because 1 is not greater than 2. Not simply flips a false over to true or a true over to false. Because the expression is false, the Not operator makes the result true. As a result, the VBScript value for true, True or -1, will be stored in variable a. If the expression is null, the Not operator will return a null when applied to the expression.

The Not operator is often used when working with if-then conditionals, such as the following example:

If Not GetZip(City, State, Zip) Then

     MsgBox "The zip code could not be determined."


     MsgBox "The zip code is " & Zip

End If

This simple example calls the function GetZip. The arguments for this function are the city, state, and ZIP code. The function returns a Boolean value that indicates whether the function has succeeded. This return variable is often called a return code. The function loads the variable Zip with the ZIP code and returns True if it is successful. If the function fails, it returns vbFalse. The function could fail, for example, if an invalid state or city was passed as an argument to the function.

The conditional statement checks the return code. If it is true, the function has succeeded and the code proceeds to show the user the ZIP code. In this case, the Not operator is used instead, checking to see whether the result of the function is True or False.

Conjunction (And)

The conjunction operator compares two or more variables in some type of test. The syntax for the conjunction operator is

result = expression1 And expression2

In order to obtain True in the result variable, both expression1 and expression2 must be true. You often use this operator to make sure two or more conditions are true before performing some action. Suppose you have a Web page for making airline reservations. You have several functions in your code: one to get the customer's name and address, one for the origination point, one for the destination, and one for the day he or she wants to travel. In order to book the reservation, each function must succeed. If any of them fail, the reservation cannot be made. The following statement is an example of what could appear in a VBScript code segment:

OkayToReserve = 

GetCustomer(Name, Address, Phone) And 

GetDepartureCity(DepartCity) And 

GetDestinationCity(DestinationCity) And 


If the function that gets the destination city from the customer, for example, does not succeed for whatever reason, your program will not accept the reservation.

This example is simple, but you get the point. Each of these functions must return True. If any one of them fails, the variable OkayToReserve will be false. You can then make a simple check to determine whether to make the reservation:

If OkayToReserve = True Then MakeReservation( Name, Address, Phone, 

DepartCity, DestinationCity, TravelDate )

VBScript lets you take a shortcut when referencing true in a condition. You don't have to explicitly compare the condition to true. If you have no comparison, VBScript assumes you are checking the true condition. The following statement is functionally equivalent to the previous example without using the True constant
If OkayToReserve Then MakeReservation( Name, Address, Phone,
 DepartCity, DestinationCity, TravelDate )

Disjunction (Or)

Another frequently used logical operator is the disjunction operator. This operator has the same syntax as the conjunction operator:

result = expression1 Or expression2

This operator behaves quite a bit differently from the conjunction operator. In this case, any of the expressions can be true for the result to be true. The result is false only if all the expressions are false. You typically use this operator when you have to make a decision in which any of a number of activities could occur, but only one must occur for the operation to proceed.

Suppose you want to call a function on your Web page that processes an order for flowers. If you have five varieties of flowers, the customer could order one or more types. You simply want to see if any of them are on order. All it takes to process an order is a request for one type. The following code segment handles this request for you:

If Order1 Or Order2 Or Order3 Or Order4 Or Order5 Then


End If

In this case, five variables exist that are true or false, depending on whether the user wants to order flowers of that type. If the user wants to order flowers of any type, the script calls the OrderFlowers function. That function can then determine the specifics of the flower order.

Additional logical operators, such as the exclusion operator (Xor), the logical equivalence operator (Eqv) and the implication operator (Imp) are discussed in detail in Teach Yourself VBScript in 21 Days from

String Concatenation

One special operator does not fit in any of the other classes. This operator, called the string concatenation operator, is represented by the & symbol.

String Concatenation Using the & Operator

You use the string concatenation operator to merge two strings together. If, for example, one variable holds the string

First_Name = "Buddy"

and the second holds the string

Last_Name = "Bird"

to form a complete name, you need to concatenate these two strings. The syntax for the concatenation operator is

result = string1 & string2 & ... & stringn

String Concatenation Using the + Operator

You should know one more thing about string concatenation. As you begin to see examples of VBScript code on the Internet, you might sometimes see strings concatenated using the + operator, rather than the & operator. For example, you can build a name with this code:

Name = First_Name + " " + Last_Name

This statement would correctly build the string "Buddy Bird" for you. Although you can indeed use the addition operator to concatenate strings, you're not always guaranteed a correct result because the addition operator is designed for numeric values. It can handle strings, but when strings are mixed with numbers, VBScript can get into an ambiguous state, not knowing exactly how you want to concatenate the values. If, for example, one of the expressions is a number and the other is a string, the + operator gives you an error:

Dim a, b, c

a = 10

b = " Apples"

c = a + b

MsgBox c

When VBScript encounters the expression c = a + b, a type mismatch error will result. Instead of trying to add a number and a string that cannot be translated into a number, you should use

Dim a, b, c

a = 10

b = " Apples"

c = a & b

MsgBox c

and you will store "10 Apples" in the variable c.

You must enclose literal numbers in quotes if you want to treat them as strings when you concatenate them to other strings. Because this step is not very convenient and requires extra thought, it's safer and better to use the & operator whenever you're concatenating strings. Any technique that helps reduce potential errors in your code is always a wise decision.

Operator Precedence

Now you have seen all the operators VBScript has to offer. For each type of operator-arithmetic, comparison, and logical-you have seen the order of precedence. What happens when operators from different categories are all combined in the same statement? What is executed first?

VBScript first attends to the arithmetic operators, followed by the string concatenation operator, the comparison operators, and the logical operators, as summarized in Table 22.2.

Table 22.2. Operator precedence summary.

Exponents (^)
Negation (-)
Multiplication (*), division (/ and \)
Modulo arithmetic (Mod)
Addition (+), subtraction (-)
String concatenation (&)
Equality (=)
Inequality (<>)
Less than (<)
Greater than (>)
Less than or equal to (<=)
Greater than or equal to (>=)
Object equivalence (Is)
Negation (Not)
Conjunction (And)
Disjunction (Or)
Exclusion (Xor)
Logical equivalence (Eqv)
Implication (Imp)

When an expression has more than one operation, each part of that expression is evaluated in this order from left to right across the expression.

Intrinsic Functions

VBScript contains a wide variety of functions you can use to enhance and empower your applications.

Dates and Times

The functions that follow can work with a date, a time, or a time and date. In VBScript, dates and times are often stored together. The date subtype is viewed as representing both a date and time in its own format.

Date, Time, and Now

Some of the easier functions to use are Date, Time, and Now. Date returns a character string with the current date. Time returns a character string with the current time. Now returns a character string with the current date and time.

Date, Time, and Now lead to the same results. The difference is that whereas Date returns an individual date and Time returns an individual time, Now returns both the current date and time, combined into one string. To see the current date and time, for example, you could enter the following statement in a script:

Msgbox "Current date / time is " & Now, 0, "Using now"

Alternatively, you could use the Date and Time functions to provide the same type of feedback to the user.

Msgbox "Current date / time is " & Date & " " & Time, 

             0, "Using date and time"

Year, Month, Day, Weekday, Hour, Minute, and Second

When you use these functions, working with pieces of a date and time string is easy. If you need to use just the current hour figure to determine what type of data a program runs, you can parse out this information with the Hour function. The same type of helpful function is available if you need to know what day of the week a certain date fell on. Use the Weekday function to get your answer. You don't have to write a detailed procedure to parse this information out of a date because it is already there.

Several similar functions handle dates and extract information. Year returns a number representing the current year, Month returns an integer representing the current month, Day returns an integer representing the current day number, and Weekday returns numbers 1 through 7 to represent Sunday through Saturday, respectively. All the functions take a date specification as an argument and return data about that date supplied as an argument. The date specification argument is typically one of your variant variables, but it could also be the function Now or anything else in date and time format. The following statement shows these functions in use.

Dim dtmCurrent

' Start out with current time as value to use

dtmCurrent = now

Msgbox "Current year is " & Year(dtmCurrent) & "; month is " &_

        month(dtmCurrent) & "; day is " & day(dtmCurrent) &_

        ": weekday is " & weekday(dtmCurrent), _

        0, "Using year/month/day/weekday"

The time-based functions work much the same. Hour, Minute, and Second can derive this information from the time supplied as an argument. Here is an example of these functions in use.

dim dtmCurrent

' Start out with current time as value to use

dtmCurrent = now

MsgBox "Current hour is " & Hour(dtmCurrent) & "; minute is " &_

       minute(dtmCurrent) & "; second is " & second(dtmCurrent) _

       0, "Using hour/minute/second"

These code examples are easy to write because the functions are very straightforward to use.

VBScript uses additional functions such as DateSerial, TimeSerial, CreateDate,and IsDate. These and other functions are discussed in Teach Yourself VBScript in 21 Days from

Advanced Math

Many computer programs written today require some type of math to process user data and provide results. Many require extensive mathematical operations. The ability to carry out precise calculations is an integral part of programming. It comes as no surprise then that an important part of any programming language is the mathematical capabilities it supports.

Rounding and the Integer Functions-Fix and Int

When you deal with numbers and produce results, you need to handle them in different ways. You will want to keep some results, such as the grade point average of a student, in decimal format. Other results, such as the total number of employees you need to hire to staff a factory based on average staffing history, you might need to round. After all, you would have trouble hiring 20.7 workers if your company doesn't use part-time help. Your best bet is hiring 21 workers. Still other results might need to be truncated. If you are writing a program that provides billing estimates based on the number of days a patient stays at a hospital, but you only charge for full days, you might treat a total of 14.2 days or 14.9 days as simply 14 days.

VBScript provides several easy-to-use functions to carry out all these tasks.. First of all, consider the case of truncating. Truncating a decimal point is essentially the same as returning the corresponding integer. The Int function serves this purpose by returning the integer portion of a number. The statement

MsgBox Int(14.9)

displays 14, as does the statement

MsgBox Int(14.2)

These statements work exactly the same way with the Fix function. Fix also truncates a number to display its integer representation. For example, the following statement displays 15:

MsgBox Fix(15.7)

One difference between these two functions-and it is a subtle one related to rounding negative numbers-is that Fix truncates a negative number so that the value is greater, and Int produces the negative integer that is less than the value supplied. The following statement displays -15:

MsgBox Fix(-15.7)

But the next statement displays -16 instead:

MsgBox Int(-15.7)

If you need to round a number rather than truncate it, you can always build in the rounding yourself. If you add .5 to a decimal number and then take the integer value using Int, the result is to round it to the next higher integer if the number originally contained a decimal portion greater than .5. For example, if VarA contains 1.7, then the following statement displays the result 2.0:

MsgBox Int(VarA + .5)

An easier and slightly different way to round is built into VBScript. The Cint function will round a number to the nearest integer. If decimal values are less than .5, Cint rounds the number down. If decimal values are greater than .5, Cint rounds the number up. If the decimal portion of a number is exactly equal to .5, then it is rounded to the nearest even number. For example, 7.5 would be rounded up to 8. Because 7.5 is between the two even numbers 6 and 8, 8 is the nearest even number and is selected as the rounding result. Likewise, 6.5, sandwiched between 6 and 8, would be rounded down to 6.

A good way to think of these functions is in terms of a number line. If you really want a number to be rounded rather than truncated, you should use Cint. This function moves you to the closest integer on the number line and chooses the closest even integer when the choice is a toss-up. If you simply want to truncate the number, and you always want to truncate to a lesser value, then Int is the way to go. Int always advances you left on the number line to the previous integer. If you do have a special situation where you want to truncate, but you always truncate closer to 0, then use Fix. This function will always advance you to the next closest integer to 0, moving you left on the number line when you started with a positive number and right on the number line when you started with a negative number.

VBScript has many additional math functions such as Fix, Log, Exp, Sqr, Sin, Cos, Tan, Atn, Trig, Randomize, Rnd, and Mod. These and other mathematical functions are discussed in Teach Yourself VBScript in 21 Days from

The MsgBox Function

Sometimes, particularly in a programming language, simple is beautiful. An easy-to-use programming function or element is less likely to cause you bugs, which saves you time, effort, and the pain of banging your head on the monitor in frustration. Simple means good, clear, maintainable code. The message box function is just that-good and simple!

You have seen examples of the message box earlier in this chapter. For example, you can insert a statement in your code that displays a small window with the message Break time! with just 20 characters of typing:

MsgBox "Break time!"

When this code statement is carried out, a window containing this message pops up in the middle of the screen. Not only does the user see this message in a nice little window, but that window even comes with a handy acknowledgment button. The window hangs around until the user clicks on the button to make it go away.

First, consider the issue of interaction. Users could click OK because it is the only choice! The purpose of forcing users to select OK is to make sure that they read the message. The OK button, in this case, is simply an acknowledgment button.

You can use MsgBox to get much more information from the user than simply an acknowledgment. The second parameter of the function is used to specify message box attributes. One attribute that you can specify is the type of buttons to include in the message box. Consequently, your selection affects the type of information that the user returns to your code.

A specific integer number specifies each type of button choice attribute. The values and purposes are summarized in Table 22.3.

Table 22.3. VBScript button constants.

Show only OK button
Show OK and Cancel buttons
Display Abort, Retry, and Ignore buttons
Show Yes, No, and Cancel buttons
Show Yes and No buttons
Show Retry and Cancel buttons

You can use button attribute constants to request different combinations of buttons as well. All the available combinations are documented in Table 22.3. Most of these combinations give the user the opportunity to provide more feedback to the script than just a simple acknowledgment. The vbYesNoCancel constant, for example, provides three choices for the user, as shown in the next example:

rc = MsgBox( "rc = MsgBox ""Text"", vbYesNoCancel + vbExclamation, ""Title"" ", _

      vbYesNoCancel + vbExclamation, "vbYesNoCancel")

The script can then interpret which button the user selected and perform further processing based on that response. But that's not the whole story of the second parameter. The second parameter has two pieces joined by a plus sign. The button indicator code is on the left side. What's that on the right side? It's a value that indicates the icon to display with the message box.

When the MsgBox function is used, it sends a return value back to the statement that called it. This return code can be assigned to a variable of any name, although the convention of rc for return code is often used. The return code will indicate which button the user selected. This value will be one of the ones shown in Table 22.4.

Table 22.4. VBScript button response values.

Returned by MsgBox if OK is selected
Returned by MsgBox if Cancel is selected
Returned by MsgBox if Abort is selected
Returned by MsgBox if Retry is selected
Returned by MsgBox if Ignore is selected
Returned by MsgBox if Yes is selected
Returned by MsgBox if No is selected

If you have used programs in a Windows environment, you probably know one very important aspect of the message box window: It is modal. Once a message box is presented, users must respond to it before they can interact further with that Web page. Modality is great news from a script-programming standpoint. When a script puts up a message box, you know that by the time the next code statement is carried out, the user will have already provided a response to that message. Consequently, you have a high degree of control over the interaction. You know the user has to respond to your message, and you know that you will have a record of the user's response in the statement after the message.

Input Boxes

The input box function, InputBox, provides a separate modal window much like the message box. You can use it to present a prompt message to the user and collect an input string that is returned back to the script. The syntax of the function takes the following format:

ResultVar = InputBox(prompt_message, optional_title,

optional_default_response, optional_x_position,

optional_y_position, optional_helpfile,

optional_helpfile_context )

The first parameter is the prompt message; it prompts the user for a response. The prompt message is required, and the rest of the parameters are optional.

The next parameter is the title of the window, which is displayed in the top caption area. If a title is not supplied, Visual Basic will appear in its place.

The third parameter is the default response, which will appear in the text input area that is supplied for user input when the input box is generated. The default response is a response that the user is likely to provide. To accept the default, he or she can simply select OK without typing in any text. To provide a specific response, the user simply types the response and then selects OK. The new input will automatically replace the highlighted default; no backspacing or deletion is necessary.

The fourth and fifth parameters control the placement of the input box in x and y coordinates from the top of the screen. In the sample, the X and Y were specified to be 0, so the input box appeared at the top-left corner of the screen. If no values are supplied, the input box appears centered horizontally on the screen and one third of the way down.

The sixth and seventh parameters of the InputBox function call are for help file and help file context information. The help file support for the InputBox is the same as that for the message box.

The manner of retrieving the user response for an InputBox call is also similar to that of MsgBox. After the user enters a string into the input area and clicks OK, that user-supplied value is returned.

Controlling the Flow of Code

In this section, you will learn how to control the flow of your programs. This subject is very important when you want your programs to make on-the-spot decisions or execute based on what the user wants to do. You will learn about all the ways you can construct and control the order in which your code is executed. You will learn all the VBScript control structures and see several examples of how you can apply them. You will also learn which structures are particularly applicable and useful in various situations.

Using Control Structures To Make Decisions

Fortunately, VBScript gives you a variety of ways to direct the flow of your code with mechanisms called control structures. They are called structures because you construct your code around them, much like you build and finish a house around its structure. Control structures are like the wood beams and boards in your house that all of your rooms are built upon. You can use each control structure to make your code travel in different ways, depending on how you want a decision to be made. In this section, you will learn about two control structures used in VBScript to choose one path of code versus others. Later, you will see the control structures that choose the same code path over and over based on criteria you specify.

A control structure is a combination of keywords in code used to make a decision that alters the flow of code the computer executes


The first control structure you should know about is If...Then. The syntax for this control structure is given as

If condition = True Then

     ... the code that executes if the condition is satisfied

End If

where condition is some test you want to apply to the conditional structure. If the condition is true, the code within the If and End If statements is executed. If the condition is not true, the code within these statements is skipped over and does not get executed.

Rather than using the expression
If condition = True
you can use the expression
If condition Then
instead. VBScript automatically checks to see if the condition is true if you don't explicitly say so. Similarly, if you want to check to see if an expression is false, you can check to see if the condition is equal to false
If condition = False Then
or you can have VBScript check the Not true condition
If Not condition Then
These conventions can be used interchangeably throughout the book.


The control structure called If...Then...Else is represented as

If condition = True Then

    ...this is the code that executes if the condition is satisfied


    ...this is the code that executes if the condition is not satisfied

End If

What if you had a few other cases you wanted to test? You're in luck: You can do as many tests as you want by simply placing more ElseIf statements between the first If statement and the End If statement. The syntax of such a structure looks like this:

If condition1 = True Then

   ...the code that executes for condition1

ElseIf condition2 = True Then

   ...the code that executes for condition2

ElseIf condition3 = True Then

   ...the code that executes for condition3

End If

where you can have as many ElseIf statements as you want. Notice that the terms Else and If must be concatenated as ElseIf, whereas End and If are separate, as End If. You can use the If...Then and If...Then...Else control structures to control the flow of your code based on decisions made within your code. For more information on these structures, refer to the book Teach Yourself VBScript in 21 Days from

The Select Case Structure

In cases in which you have to perform a large number of tests on the same expression, you can use the Select statement. The Select statement often makes your code easier to read and interpret versus a long list of Else and Else If statements. The Select Case structure is defined as follows:

Select Case test_expression

    Case expression-1

      ...this is the code that executes if expression-1 matches test_expression

    Case expression-2

      ...this is the code that executes if expression-2 matches test_expression

    Case expression-3

      ...this is the code that executes if expression-3 matches test_expression




    Case Else n

      ...this is the code that executes if expression-n matches test_expression

End Select

where expression-1, expression-2 and expression-3 are one or more expressions that must match the test_expression in order for the code below each Case statement to execute. As you can see, the same condition is evaluated throughout the structure. Only one case is executed when VBScript travels through. If more than one case matches, only the first one is executed. If none of the cases match, the code underneath the Case Else section is executed. The Case Else section is optional. Therefore, if you don't include a Case Else section, none of the code within the case statement is executed.

Consider the following example that prints a message to the user based on the user's home state:

Select Case State

   Case "Michigan"

      Message = "Michigan is a wonderful state to visit if you enjoy " &

                "fresh water lakes."

   Case "Virginia"

      Message = "Visit the Commonwealth for a wide variety of historical " &

                "landmarks and beautiful mountain-scapes."

Case "Arizona"

      Message = "Arizona is a wonderful getaway for those who love heat " &

                "with low humidity"

   Case "Colorado"

      Message = "Colorado is almost unsurpassed for its " &

                "majestic mountains and rivers."

Case Else

      Message = "No specific information is available about this state."

End Select

Using Control Structures To Make Code Repeat

On occasion, you will need to write code that repeats some set of statements. For example, you might need to perform some calculation over and over, or you might have to apply the same calculations or processing to more than one variable, such as changing the values in an array. This section explains the VBScript control structures that enable you to write code that repeats.


The first structure is often referred to as the For...Next loop. The syntax for this structure is

For counter = start to finish

   ...code that gets repeated


where counter is a variable used for counting purposes that begins at the number specified by the start variable and counts up by one, each time executing the code within the structure, until it reaches finish. Usually, counter is incremented by one each time through the loop, although you can change the value of the increment. I'll show you how to do this in a moment, but first, check out the For...Next loop in action.

Suppose you have an array called Salaries that contains 30 elements, and you want to set all these elements to a value of 30,000. You could enter the following code:

Salaries(0) = 30000

Salaries(1) = 30000

Salaries(2) = 30000




Salaries(29) = 30000

If you did it this way, you would have to enter 30 lines of code. Rather than do all that work, however, you can use a much more efficient loop. You're still repeating the same operation 30 times, but each time, you're assigning the value to a different element in the array. Try entering the following code:

For i = 0 to 29

   Salaries(i) = 30000


The For...Next loop is quite flexible because you can tell VBScript how much you want the counter variable to be incremented each time through the loop. You can also decrement the counter rather than increment it. How do you do this? The counter is incremented by a value of one each time through the loop unless you specify otherwise. You can do so through the use of the Step keyword like this:

For counter = start to finish Step increment

   ...code that gets repeated


where increment is a variable or value that tells the loop how much to increment the counter each time through the loop. As before, the moment counter falls outside the range of start and finish, the loop will stop.


The next conditional structure is the powerful Do...Loop structure, and one variation of this loop structure is the Do While...Loop. The basic syntax for this structure is

Do While condition

   ...code within the loop goes here


where the condition is either true or false. As long as the condition is true, the code within the loop gets executed. Once the condition becomes false, the loop stops and the code after the loop is executed. The only way for the program to break out of the loop is if the condition becomes false or if an Exit Do statement is encountered somewhere inside the loop. Consider the following example shown in Listing 22.1.

Listing 22.1. Using the Do While...Loop conditional structure.

Again = True

DoubleIt = 1

' Keep doubling the number as long as the user desires

Do While Again = True

       '  Show current results and prompt to see if we should continue

       If MsgBox("Current total is " & DoubleIt & ". Double it again ?", 

       vbYesNo) = vbYes Then

          DoubleIt = DoubleIt * 2


          Again = False

       End If


In Listing 22.1, the first line of code sets the variable that gets tested in the loop equal to true. The second line sets the variable that gets doubled in the code equal to one. Setting the loop variable equal to true enables the loop to get off and running because the third line says, "If Again is true, enter the loop." Because the variable has just been set to true, the loop begins. The first statement in the loop displays the result to the user. Because nothing has been doubled yet, the result is one-the initial value of the DoubleIt variable.

When the results are displayed, the user is asked if he or she wants to continue. If the user chooses to go forward, the variable DoubleIt is multiplied by two. When the program hits the Loop instruction, it will return to the top of the loop and once again check to see if the condition is set to true. Because the condition has not changed, the loop executes again. It will continue to execute until the user chooses not to continue. Once that happens, the variable Again is set to False. Now, when Loop is reached, the code swings back up to the top of the loop and evaluates the condition once more. This time, the condition is false, so the loop does not execute again. The code moves on beyond the loop.

VBScript has many additional conditional structures, such as Do...Loop While, Do Until...Loop, and Do...Loop Until. For a comprehensive discussion of all the conditional structures available in VBScript, refer to Teach Yourself VBScript in 21 Days from

Building a Home for Your Code

In this section, you will learn how VBScript code is organized. VBScript, like most other languages, stores code in procedures. Procedures come in two varieties: subroutines and functions, each of which is explored in this section.


The first type of procedure is the subroutine. You declare subroutines using the Sub keyword and end them using the End Sub statement. The structure of a subroutine is

Sub Subroutine_Name(argument1, argument2, ..., argumentn)

   ...code within the subroutine

End Sub

where Subroutine_Name is the name of the subroutine and argument1 through argumentn are optional arguments, often called parameters, that you can pass to the subroutine. If you choose not to pass any arguments to the subroutine, the parentheses are optional, as you will see in a moment.

You can design a subroutine to require that the code statement that calls that subroutine provide one or more arguments, or variables that the subroutine can work with. Any time you need preexisting data to perform the task within the subroutine, arguments are very helpful. For example, the argument that the following subroutine accepts is actually a message that the subroutine displays to the user.

Sub ShowMessage(CurrentMessage) 

   MsgBox CurrentMessage, vbOkOnly, "Important Message"

End Sub

In this case, CurrentMessage is the argument, and it is treated like any other variable in the subroutine. It is treated exactly as if it had been declared with a Dim statement with one very important difference. The CurrentMessage argument variable starts out pre-initialized with a value that was supplied by the code that called this subroutine.

Frequently, a subroutine might not require any arguments, and you can drop the parentheses. For example, if you have a subroutine that simply displays information to the user, it doesn't need any arguments, as in the following code:

Sub ShowAboutMessage

   MsgBox "This Web page was designed by the WebWizard."

End Sub

Because the code lists no arguments, it does not require the parentheses. On the other hand, if you declared a procedure using one or more arguments, you'd use the parentheses as shown in the following example:

Sub ShowAboutMessage(Message)

   MsgBox Message

End Sub

Now that you've learned how to create a subroutine, how do you call one? You can call a subroutine throughout the rest of the application once you've declared and created it by using the Call keyword or by entering the name of the subroutine on a line of code. For example, to call a subroutine called ShowMessage, you could enter

ShowMessage "This is the message."

You could also use the Call keyword and enter

Call ShowMessage("This is the message.")

Although the choice is up to you, I generally recommend that you always use the Call statement when calling subroutines for the sake of readability.

The code within your subroutine will execute until one of two things happens. First, the subroutine might get down to the last line, the End Sub line, which terminates the subroutine and passes the baton back to the caller. This statement can appear only once at the end of the subroutine declaration. The second possibility is that VBScript could execute

Exit Sub

when placed inside the subroutine. You might use Exit Sub if you need to provide more than one exit point for the subroutine. However, you shouldn't need to use this statement very often if your subroutine is constructed properly.


The second type of procedure is called a function. Like a subroutine, a function also holds a series of VBScript statements. The only difference is that a function actually returns a value to the code statement that called it. You've already seen earlier in this chapter how you can fill a variable with a value supplied on the right side of an assignment statement:

ZipCode = 49428

In the same manner, you can fill a variable with a value supplied by a function you define:

ZipCode = GetZipCode("Jenison")

As with the subroutine, the flow of code is redirected to the function while the code within the function executes. Once the function has finished executing, control returns to the code that called the function, the value from the function is assigned to the calling code, and execution resumes.

To declare a function, use the Function keyword instead of the Sub keyword. You end functions using the End Function statement. The structure of a function is

Function Function_Name(argument1, argument2, ..., argumentn)

     ...code within the function

End Sub

where Function_Name is the name of the function and argument1 through argumentn are optional arguments you can pass to the function. As with the subroutine, the parentheses are not required if no arguments are passed to the function.

Now that you've seen how to declare a function, you need to know how to call it. The benefit of using a function is that you can pass back a piece of data to the caller. The subroutine does not enable you to do this because it does not return anything. You will see a way to change variables in the calling code with a subroutine later in the chapter, but the function is a better way to transfer data back and forth. To call a function, you simply use the following syntax:

return_variable = function_name(argument1, argument2, ..., argumentn)

Notice that the syntax for a function is quite a bit different from the syntax for a subroutine. Here, you can assign the function to a variable (or another expression that can be updated with a value, such as a property), or you needn't assign it to anything. Also, the parentheses are optional. Even if you pass arguments to the function, the parentheses are not required. This syntax is quite a change from the familiar parentheses Visual Basic requires for functions.

Suppose you have a function called GetAge. To use the GetAge function, you could enter the statement

UserAge = GetAge()


UserAge = GetAge

Notice that this function doesn't need any arguments and that the result is assigned to a variable named UserAge. The following function requires three arguments-hours, minutes, and seconds-and returns the number of seconds:

Function GetSeconds(Hrs, Min, Sec)

   GetSeconds = Hrs * 3600 + Min * 60 + Sec

End Function

You could then call this function using a statement like

NumSeconds = GetSeconds(2, 34, 25)


NumSeconds = GetSeconds 2, 34, 25

where the total number of seconds is returned to the variable NumSeconds.

To exit a function, you use the same method as when you exit a subroutine, namely, the End Function statement. This statement can appear only once at the end of the function declaration. You have seen this statement used in the functions discussed so far. You can also use the statement Exit Function to break out of a function in the same way as you used the Exit Sub statement to exit a subroutine. As before, exiting a function naturally when your code reaches the final End Function statement is a better technique than using an Exit Function line of code to terminate the function in the middle of the statements. The code is simply easier to follow when you avoid such forced exit statements.

Passing Arguments into Procedures

When you call a procedure, you either provide a copy of a variable to a procedure so that it has a local copy to modify if necessary or refer the procedure to the original variable itself. Either way, the procedure cannot modify the variable owned by the caller. If you refer the procedure to the original variable, you are, in effect, supplying the memory address of that variable to the procedure. However, VBScript hides the memory address details from you. From the programmer's perspective, you are simply providing the variable name to the procedure. But VBScript does not enable you to change the variable-the interpreter will trigger an error when the Web page loads, if you try to do so.

The current VBScript in beta Internet Explorer does not support the "ByRef" parameter familiar to many Visual Basic programmers. In Visual Basic 4.0, for example, if you use a ByRef parameter, you can make changes to that variable within the subroutine that defined the parameter and the changes are reflected back to the variable supplied in that parameter position by the calling code. This capability might be introduced in subsequent releases. You might want to check the current documentation to ascertain the implementation level if you are interested in this feature

Passing by value means that a copy of the original value is given to the procedure. The procedure can change its own copy, but it won't affect the original owned by the caller

To refer the procedure to the original without giving it a copy of the variable, you omit the ByVal keyword. This case is the default and is called passing a variable "by reference." If you try to modify a variable passed to a procedure by reference, VBScript displays an error message when the Web page loads into the browser. The procedure can read the contents of a variable passed in by reference, but it cannot change its contents because the procedure doesn't own the variable.

Passing by reference means that the procedure is allowed to read the variable owned by the caller. The procedure is not allowed to change the value of the variable because it does not own that variable

If you wish to pass variables into a procedure by value, you simply declare the procedure using the format

Sub Subroutine_Name(ByVal argument1, ByVal argument2, ... ByVal argumentn)

when creating a subroutine and

Function Function_Name(ByVal argument1, ByVal argument2, ... ByVal argumentn)

when creating a function. To pass variables by reference, you simply omit the ByVal keyword as shown here for a subroutine:

Sub Subroutine_Name(argument1, argument2, ... argumentn)

and here for a function:

Function Function_Name(argument1, argument2, ... argumentn)

Event Procedures

When you work with controls and other components, you frequently interface with them using event procedures. Event procedures are subroutines that are called automatically by the browser. They are different from regular subroutines in that regular subroutines must be called within the program by statements you write or else they are never used. An event procedure is called as a result of some action taken by the user, such as clicking a command button or checking a box on a Web page, or by the system, such as detecting that a predefined timer has expired.

An event is a subroutine called automatically by VBScript as a result of a user or system action. Although the programmer must manually specify subroutines and functions calls through normal calls in code, event subroutines are called automatically as a result of what they represent. For example, you can define a subroutine to be carried out when the user clicks on a particular button by means of a special name. Then, when the user clicks the button, the button control object itself generates an "OnClick" event. VBScript responds to this event by calling the named subroutine associated with the event

You don't have to worry about calling event procedures in your code because they are called automatically by the system and the browser, but you do need to create them if you want to write code that responds to these events. For example, if you place a button on your Web page, you probably want your program to respond in some way when the user clicks it. If you construct an event procedure, you can write the code to do just that. If you fail to place the event subroutine in your code, however, your users can click the button all day long, and nothing will happen because no event procedure is available to process the click events.

The rules for creating and naming event procedures are more rigid and structured than regular procedure naming rules. First of all, the naming conventions for an event procedure are very specific. Except with some special cases discussed later in the chapter, you can't just name an event procedure anything you want. To name an event procedure, you must know two things: the name of the control, or component, and the name of the event you want to respond to. Suppose, for example, you have a command button on your Web page labeled TestButton. Buttons have an event called OnClick that you can write code for. This event occurs when the user clicks the button. To create an event procedure for this action, you must name your procedure


Notice that the name of the control comes first, followed by an underscore character, followed by the name of the event. You must spell everything correctly, or else VBScript will be unable to connect the event procedure to the button. The rule for assigning a name to a control or component is

Sub ControlName_EventName()

where ControlName is the name of the control and EventName is the name of the event corresponding to the control. You'll learn more about event procedures later in the chapter when intrinsic HTML controls and ActiveX controls are introduced.

Method Procedures

You might have also heard of method procedures. Method procedures are similar to predefined procedures you can call, but they are provided by an object. You can't actually see the code for them, nor can you create them. Objects can have a set of methods that were created when the programmer designed the object.

A method is an object-associated procedure you can call. Methods accomplish some specific task or service that the object provides. Methods might or might not return values, depending on what they do

To invoke the method of an object, you can simply call the method using the following convention:


where object is the name of the object and method is the name of the method. You'll learn more about objects later in the chapter.

Where To Put Procedures

Finally, you need to understand where you can place procedures in your HTML document. You can place procedures within one script tag:



     Sub GetMiles()

          ...code for subroutine

     End Sub

     Function CalculateTime(RunnerTime)

          ...code for function

     End Function



You can also place procedures in separate scripts:



     Sub GetMiles()

          ...code for subroutine

     End Sub





     Function CalculateTime(RunnerTime)

          ...code for function

     End Function



Also, notice that you do not have to store all VBScript code within a procedure. However, if you have code outside a procedure, as shown in the following example, keep in mind that this code is automatically executed in order from top to bottom when the browser first loads the Web page.


<!--  Option Explicit

   Dim Miles_Ran

   Dim Total_Miles

   Dim Start_Time

   Call InitializeVariables

   Sub InitializeVariables

      Miles_Ran = 0

      Total_Miles = 0

      Start_Time = 0

   End Sub


Intrinsic HTML Form Controls

Now that you've learned some of the important fundamentals of VBScript programming, you are ready to put these skills and techniques to practical use. Controls and objects are entities you can place on a Web page to provide an interactive user interface. You can also use controls and objects as the front ends to perform behind-the-scenes operations, such as submitting information to a program on a server.

Controls and objects are elements you can include in a Web page that enable the user to interface with the page or perform some specific task from within the HTML document

An Introduction To HTML Forms

As you can see by the title of this section, intrinsic HTML controls apply to HTML forms. You need to understand what an HTML form is and what its capabilities are in order to appreciate the roles and capabilities of the intrinsic controls. Forms serve as containers whose information can be sent across the Internet to the server that supplied the Web page to the client.

A form is a container into which you can place controls and objects. The form can transmit the values of intrinsic controls to the server for processing in response to selection of a Submit button. Even if the controls in a form are not intended to gather data for a server, a form can still provide a convenient grouping of the controls it contains

The form is particularly useful when you want to collect data on a page and then submit it to a server. An example of such a page is one that collects survey data and then submits that data for storage in a central database. You typically submit such data to a server using the HTML form submittal and CGI capabilities to launch a script on the server.

Often, you will create Web pages that simply "do their own thing" and have no need to send information back to a server. If your Web page doesn't need to use CGI to submit information to a server, then you don't need to place your controls in a form.

Now that you understand forms and the relationship that controls have to them, you are ready to examine the controls themselves. You can use HTML form controls independently of CGI. Before the development of scripting languages such as VBScript, programmers had to submit data to servers through CGI in order to give Web pages even the simplest intelligence. Now that we have a sophisticated scripting language, however, this restriction is less burdensome. Still, CGI is often vital and necessary to send data to a server, such as when ordering products or inquiring about information.

The Button Control

Buttons give the user the capability to execute VBScript code that performs some action indicated on the caption of the button. You have seen buttons in use throughout this chapter because they are such an important part of a Web page.

To create a button on a Web page, you need to use a special tag called an INPUT tag. The INPUT tag tells the browser you are about to create a control used to get input from the user. The button is just one type of control you can create using the INPUT tag. The actual input could come in the form of text, an indication of whether the user has checked the control, or a recognition of the control by clicking it. In any case, information is being exchanged with the user. The input tag takes at least two attributes: TYPE and NAME.

The <INPUT> tag is used to place intrinsic HTML controls on a Web page

The TYPE attribute is very important because it tells the browser what type of control you want to create. You use the input tag to create text controls, radio button controls, and check boxes, just to name a few. The TYPE attribute will be set equal to the keyword BUTTON. As you will see, other keywords are used for the other control types.

The second attribute that you must supply is the NAME attribute, which gives the control a name. Why would you want to name a control? To work with a control, you have to refer to it, and to do that, you must give it a unique name. The name can be any string as long as it starts with a letter.

You can use many more standards to help make your code clear, readable, and easy to maintain. You won't really understand all the recommended standards until you've been exposed to the full VBScript language. Refer to the book Teach Yourself VBScript in 21 Days for detailed coverage of all the important standards

When you work with button controls, you want to set one more attribute-the VALUE attribute. The VALUE attribute sets the caption of the button. The caption tells the user what the button does. Make sure the caption of your button is descriptive enough to let the user know what happens if he or she clicks it.

Here's a simple example of a line of HTML code that creates a button:

<INPUT TYPE="Button" NAME="cmdGetCost" VALUE="Get the Cost">

The name of the control is cmdGetCost, and the caption that will appear on the Web page is Get the Cost.

How do you connect the button with your VBScript code? Quite easily, in fact. Earlier in the chapter, you learned about a special procedure called an event procedure. You saw that event procedures are designed to respond to events initiated by the user, usually on controls. To get your VBScript code to respond to a button click, you have two options. First, you can use the implicit event procedure, which has the following format:

Sub ButtonName_OnClick() your code here

End Sub

where ButtonName is the name of the button. You gave the button this name using the NAME property of the input tag when you created it. Consider Listing 22.2, which shows VBScript code that responds to the click of the button by showing the user a message box.

In HTML terms, the NAME property of the input tag is an attribute. Because you will use it as a property of the control, I use the term property here

Listing 22.2. A simple Web page with an HTML button control and VBScript code that responds to the user's click.



<TITLE>The Button Control</TITLE>



<CENTER><INPUT TYPE="BUTTON" NAME="cmdBegin" VALUE="Click to Begin"


<!--  Option Explicit

   Sub cmdBegin_OnClick()

      MsgBox "You have clicked on the command button. 

              I knew you couldn't resist!"

End Sub





As you can see, the implicit event procedure is named according to conventions. If you do not name the subroutine properly, it will not connect to the button and will never be called.

The other way of connecting a command button to code is through the explicit event procedure. Rather than create a procedure that uses the naming convention required by the implicit event procedure, in this case Sub buttonname.OnClick(), you can specify the subroutine you want to call and give it any name you like. To implement an explicit event procedure, you use a special attribute called ONCLICK when you create the button. Set the ONCLICK attribute equal to the procedure you want to call when the user clicks the button and then create the subroutine in your code. Consider the following declaration of a button:

<INPUT TYPE="Button" NAME="cmdGetCost" VALUE="Get the Cost"


In this example, the attribute ONCLICK executes VBScript code that calls the GetCost subroutine. Obviously, this subroutine must exist within the Web page. The benefit of this approach is that you do not need a unique event procedure for each event of a control. You can share a procedure among several controls, if you like. Also note that you should set the LANGUAGE attribute to VBScript. If you don't, the browser might not be able to identify what scripting language you are using. It might, for example, assume that you are using JavaScript instead. Therefore, you should always set this attribute to tell the browser what scripting language you are using.

The ONCLICK attribute not only lets you indicate procedures to be activated when the event occurs but also lets you create script code on the fly in the button definition. To do so, enclose your code in single quotes immediately after the ONCLICK attribute. For example, if you want to display a pop-up message box when the user clicks a button without triggering a separate event procedure, you can simply use the following definition for the button:


VALUE="Button One" ONCLICK='MsgBox "You just clicked on Button #1"' >

This approach is a very convenient way to throw a bit of code here and there in response to controls, but beware! The more you scatter your code around in attributes of controls, the more difficult it will be to find and debug your code later. A better idea is keeping your code within procedures and calling those procedures using the ONCLICK attribute or using the implicit event procedure approach for your controls.

You can also specify code in the ONCLICK event by enclosing it in double quotes, but you need to specify two double quotes in a row in the inner statement. They will be interpreted as one, as shown here


VALUE="Button One" LANGUAGE="VBScript"

ONCLICK="MsgBox ""You just clicked on Button #1"" " >

This rule applies to all VBScript code inside or outside script procedures.

Another interesting feature of VBScript is its support of a special block of script code that responds to a control event without placing it within a procedure at all! You can implement this feature by using the EVENT and FOR attributes in an opening script tag. Assign the EVENT attribute to a string indicating the name of the event, and assign the FOR attribute to the control to which the script applies. To write a script that presents a message box for the button cmdButton1, you could create the following script:



   MsgBox "You just clicked on button #1"



In this case, the entire script applies to one specific event. You don't need to create a procedure because the entire script is devoted to the control and event you specify. Usually, any script statements between the <SCRIPT> and </SCRIPT> tags that are not enclosed in procedures execute as soon as the page loads into the browser. However, if you use the EVENT attribute, these statements of code execute only when the event occurs. You can use this technique to declare several different scripts within the same page and enable other scripts to access data declared in each script. You could build a good event-handling approach by dedicating a separate script (enclosed in <SCRIPT> and </SCRIPT> tags) for each event instead of creating a separate procedure for each event. For purposes of clarity, using procedures within the same script might be easier because all your information is in one place.

The Text Control

Another versatile and useful control in your HTML control toolkit is the text control. This control displays a simple region on the Web page into which the user can enter alphanumeric data such as numbers, strings, and so on. Using the text control is as easy as using the button control. The text control is another of the suite of HTML input controls and is commonly defined as follows:

<INPUT TYPE="TEXT" NAME="txtCost" SIZE="10">

Notice that the TYPE attribute is set to "TEXT" rather than "BUTTON". By the way, "TEXT" is the default value of the attribute, so if you do not specify any TYPE with an input definition, you'll get a text control. Notice that you must also set the familiar NAME attribute. The typical convention when creating a text control is to prefix the name with txt. The rules for naming controls are the same for all types.

The SIZE attribute is an optional attribute that enables you to specify the width of the text control in approximate characters. Because of differences in font representation, the size of your text box will probably not be exactly that many characters wide on the page. If you omit the size, the browser determines a default size. Typically, you set the size equal to the maximum number of characters that you want the user to enter into the control. In a moment, you will learn how to restrict the number of characters that a user can enter.

The VALUE attribute is not included in the preceding example, but you can use it to assign initial text to the text box. If you want to fill the text box with data when the Web page is loaded, you can specify it in the definition. Whatever you set for the VALUE attribute will appear in the text control when the page is loaded into the browser. Listing 22.3 shows an easy way to include a text control on a Web page.

Listing 22.3. Getting a user's age from a text control and reporting it through a button using an explicit event procedure.




<INPUT TYPE="BUTTON" NAME="cmdBegin" VALUE="Get Text Control Data">



   Sub cmdBegin_OnClick()

       MsgBox "You are " & txtData.Value & " years old."

   End Sub





This code prompts the user to enter his or her age. The Web page loads the text control with a default value of 25. If the user clicks the button labeled Get Age, he or she will see a message box that echoes the age. Notice how the subroutine that responds to the button click retrieves the text control's text. The data of the text control is read by accessing the VALUE property of the control. If you wanted to place the control within a form, you would first need to refer to the form. You could refer to the form and text box on it with the name document.MyForm.txtData.Value. This name is obviously fairly long and somewhat intimidating! Fortunately, VBScript provides a shorthand method to reference the same control. You simply declare a variable, in this case called form, and set that variable using the Set keyword so that the variable refers to the form defined in the body of your HTML document. That form is referenced using the statement

Set form = document.FormName

where FormName is the name of the form you created in your HTML document using the FORM tag and NAME attribute for that form. Notice the use of the object named document. The document object represents the entire HTML document. Because a form is a specific part of the entire HTML document, the form is referred to as one of the properties of the document object. To refer to the form, you must first refer to the document and then to the document's form as shown. Once you've entered this command, you can then reference any control on the form using the following syntax:

With the cmdResult_OnClick subroutine, you must use


to refer to the text of the text control you want if you place the controls within a form. You access a control through a form, and you access a form through a document. If you use the structure outlined previously, you will make the necessary connections in your code.

Both the text control and the button control have various events and methods that you can use. Two equally useful events are the OnFocus and OnBlur events. The OnFocus event occurs whenever a control, in this case the text control, receives focus. A control can receive focus in one of two ways-the user can press the Tab key to place focus on the control, or the developer can use the Focus method to put the control into focus using code (as was the case with the Click event using the Click method). When a control receives focus, a gray box typically silhouettes the control.

Focus is a term used to indicate a control that is recognized as being the control the user is interested in. When a control on a Web page has focus, certain keys cause the control to react in some way. For example, pressing the Enter key when a button has focus simulates clicking the button

The button control discussed in the previous section supports many more methods and events, such as the OnClick and OnFocus events and the Focus method. The text control, in addition to supporting the OnFocus and OnBlur events, also supports events such as OnChange and OnSel, as well as methods such as Focus, Blur, and Select.

For a description of additional intrinsic HTML controls such as the text area control, the check box control, and the radio button control, refer to Teach Yourself VBScript Programming in 21 Days from You will find a comprehensive survey of many of the most commonly used intrinsic HTML controls.

Using Objects and ActiveX Controls

You've just looked at some of the intrinsic controls you can manipulate from your scripts. If you've been a Web page author for a while, you probably recognized the intrinsic control types; HTML has always supported the check box, text box, radio button, and other controls. Traditionally, the intrinsic controls collected input to pass to the server, but with the advent of VBScript, you can control the controls directly.

What if you want to offer some level of interaction not supported by those intrinsic controls? Some very powerful alternatives exist. One of the easiest, most powerful ways to extend those bounds is through a type of object introduced by Microsoft as part of its Internet strategy called ActiveX controls. These controls are packaged in separate files and defined to the operating system through system-wide classes. Some means is necessary to tell the browser and script the location, calling conventions, and characteristics for these components.

Defining an Object

The tag to indicate an object is one that makes perfect intuitive sense: <OBJECT>. You might need to insert objects for a wide range of purposes other than those that ActiveX controls fulfill. A Web page can consist of many types of elements, including images, controls, Java applets, video, audio, and embedded compound documents, as well as other new forms of media that might yet spring into existence. As the World Wide Web Consortium (W3C) assessed these needs, it realized that a hodgepodge of different approaches for incorporating different media, each with its own tag, was not ideal. Instead, a well-defined <OBJECT> methodology provides a general solution for all objects that you want to incorporate into a page.

The World Wide Web Consortium defines Web standards. You can find more information on the W3C working draft for "Inserting Objects into HTML" at http://www/ You can find a list of W3C working drafts at

Use of the <OBJECT> tag is best understood by looking at some simple examples, starting with the label control. You use the label control to define, through appropriate statements in an object declaration, a string of text characters that can appear anywhere on a page. So far it sounds like a heading, but you will notice a few differences. One difference is that the label text can be positioned at an angle, so it can appear diagonally across a page. Another is that the label, like most objects, can be modified by a VBScript program even after a page has been initially generated. Listing 22.4 shows the format for this object definition used to include a label control on a Web page.

Listing 22.4. The object definition declaration for an ActiveX label control.










<param name="angle" value="45" >

<param name="alignment" value="2" >

<param name="BackStyle" value="0" >

<param name="caption" value="50% off studded trail running shoes!">

<param name="FontName" value="Arial">

<param name="FontSize" value="20">

<param name="FontBold" value="1">

<param name="FontItalic" value="1">

<param name="ForeColor" value="255">


Object Attributes

The object tag is similar to the standard HTML <BODY> tag format in many respects. It has both a start tag <OBJECT> and an end tag </OBJECT>. Within the start tag, you can define additional attributes that describe characteristics common to all objects.

The CLASSID is an essential part of any ActiveX object declaration. It identifies the implementation of an object to the browser. In other words, it provides the browser with a path to the code behind an object. It describes what kind of class an object belongs to and thereby identifies the code that defines its behavior.

In the early beta versions of Internet Explorer, this class registration information consists of a cryptic-looking string of digits that corresponds to information in the registration database. The registration database, in turn, knows the location of the library file (with an OCX extension in Windows) that provides the code for this class. In later versions of the Internet Explorer, this string will probably evolve to a more easily understood program ID (such as ="PROGID:Internet.Label.1"), rather than the corresponding number reference in the previous example "clsid:{99B42120-6EC7-11CF-A6C7-00AA00A47DD2".

According to the object attribute specification, you can also identify the base location of an object in terms of a URL through the CODEBASE attribute, which means that an object can be specified as a file available on the Web. Using a URL opens the door to some of the most exciting possibilities for object components.

You can access and download controls across the Web with pages that use them. If a control doesn't exist on your system (which the browser verifies using the CLASSID), the CODEBASE URL is used, if present, to retrieve the component from wherever it resides.

Many programming environments for software that runs under graphical operating systems now provide sophisticated visual tools to incorporate components into programs. Often, you can just drag and drop a component icon onto a program interface to add the component to your program.
Fortunately, at the time of this writing, such tools are starting to appear in some forms. Microsoft's ActiveX Control Pad editor inserts object tags for ActiveX controls and represents controls visually in the left margin of the editor. This tool is currently free on the Microsoft Web site ( Short of having such a snazzy tool, however, the only way to add objects to forms is to insert the lines of code of the object declaration right into your source file.
Tools will evolve with time as the state of the art seems to change from month to month. You would be wise to check online resources and industry periodicals for the most recent information when you read this book

Object Parameters

If you've used HTML to build Web pages, the attributes of the object tag are probably somewhat familiar to you. The attributes are common to other tags such as <BODY> and <IMG> as well as <OBJECT>. Another aspect of the object tag-the <PARAM> tag-is unique to it. <PARAM> specifies object parameters within an object definition. An object parameter is a characteristic of an object that is defined by the object itself, rather than by the HTML standards. If you have experience with Visual Basic or an object-oriented programming language, you can picture a parameter as a property of the object.

<PARAM> is a tag that is embedded between the <OBJECT> and </OBJECT> tags. <PARAM> requires no ending tag and carries with it just two main attributes: NAME and VALUE. NAME is used to designate the name of a property, and VALUE determines its initial value. If you refer to Listing 22.5, you can see that the label ActiveX control object definition defines a font name property:

<param name="FontName" value="Arial">

An object's <PARAM> tags perform essentially the same function as do properties within Visual Basic 4.0

You first assign object properties when authoring a page to create the initial state of an object. You also will probably reference many properties in your scripts to control the behavior and characteristics of an object. You can reference a specific property in your code by designating the ID of the object, a period to indicate that what follows is a property, and then the specific property. When you reference the name of the object and property in a statement, the corresponding value is returned. When the object and property indicator appear on the left side of an assignment statement, such as

"lblAd.Caption = "Sales Off"

the object's property value changes to the new value indicated in the assignment. Being able to set and retrieve the value of object properties provides a powerful means to interact with controls within your scripts. You can write code to inspect and control any aspect of the controls you incorporate in your programs.

ActiveX Controls

ActiveX is a technology standard that was introduced by Microsoft in March 1996. It defines a standard approach for implementing controls that can be easily integrated into applications, including Web pages. You can obtain ActiveX controls from Microsoft or from third-party vendors, or you can write them yourself.

Microsoft has provided many free-of-charge ActiveX controls already, and you can expect more to be available to help foster growth of their Internet and operating system environments. In addition, many companies sell ActiveX controls that perform specific tasks. Purchasing a control is usually less costly than expending the labor to write the same code yourself, so a steady market for controls exists. Suppose, however, that you want to integrate some type of functionality into your program but cannot locate a control on the market that serves the purpose. The prospect of writing it yourself and using it in many VBScript programs might start to sound appealing.

Using Label Control Properties

The following sample line of code shows a VBScript statement that changes the value of the label control caption property. The name of the control, lblAd, was designated when the object was declared earlier in the HTML source through the <OBJECT id="lblAd"> attribute. Caption was designated as a property within this object declaration by the <PARAM NAME="Caption"> parameter. This example assigns a new string to the caption property of the label object. This statement could appear within any block of script code; for example, it could execute in response to a button click. As soon as the script code containing this statement finishes, the new caption is displayed for the label:

lblAd.caption = "This is a new caption!"

In addition to manipulating object properties, you can also use object methods in your code. When you use an object's method, you are essentially calling prepackaged function or subroutine calls from the object. In the following example, the lblAd control's AboutBox method is called to display an About box associated with that control. The AboutBox method is an intrinsically defined method or function built into the control. You do not have to explicitly define such methods in your Web page <OBJECT> declaration. You get access to all the methods of an object simply by including the <OBJECT> tag.

' Show the about box for this control


As you can see, you can weave a lot of programming around controls. You can set properties of ActiveX controls and call methods that trigger code performed in the control. You've covered all the bases except one. What if the user interacts with the control on the Web page, or the control reaches a certain state you want your code to react to? How can you write code that reacts to these events? (Recall that events are predefined conditions of the control with which you can associate code. When the condition occurs in the control, your code is triggered.) ActiveX controls provide the same solution for handling events as you read about in the section on intrinsic controls.

Consider again the label control. A predefined event for the label control is the Click event. If the user clicks a label, the control's Click event handler subroutine is performed (if one is defined in the script). The block of code in Listing 22.5 is the event-handling code for the Click event of the label.

Listing 22.5. The Click event for the label control.



   Sub lblAd_Click

        MsgBox "Our studded trail shoes are especially well-suited " & _

               " for running over glaciers or through muck-covered " & _

               " streams with nary a slip!",0,"A Steal at $49.00!"

   End Sub



The name of the lblAd_Click subroutine associates this code with the label's Click event. The first part of the subroutine name, lblAd, associates it with the ID of the ActiveX control object. The underscore (_) is the notation that indicates an event definition might follow. Then, because the Click that follows is the name of a predefined label event, the code in subroutine lblAd_Click will be performed whenever that specific label is clicked. Whenever the user clicks the label, the message box pops up to provide more details.

In addition to the label and timer controls, ActiveX has the New Item, Chart, Preload, and Layout controls. Microsoft might have introduced more controls since this book was printed. Refer to Teach Yourself VBScript in 21 Days for much more information about these ActiveX controls


This chapter presented an overview of the VBScript language. You learned how to create variables, apply operators to those variables, work with strings, use math functions and other specialized functions, control the flow of code with conditional structures, and present and query information from the user. Then, you learned how to include intrinsic HTML controls, objects, and ActiveX controls in an HTML document with VBScript. These concepts are all fundamental to your understanding of VBScript. In the next chapter, you will see some actual Web pages that use the concepts discussed in this chapter.