Chapter 30

Introducing Visual Basic Script (VBScript)

by William Robert Stanek


CONTENTS

Microsoft's Visual Basic Script (VBScript) offers the functions of a programming language and the simplicity of a technology streamlined for the Web. With VBScript, you can bring your Web pages to life with real-time interaction; there's no more waiting for a server to respond to button clicks and mouse movements. A click of a button gets an instant reaction, and the movement of the mouse over an object brings the object to life.

When you enhance your Web pages with VBScript, you insert scripts directly into your pages. Because VBScript is a subset of Microsoft's Visual Basic, your scripts resemble programs written in Visual Basic. If you aren't a programmer, don't worry. The wonderful thing about VBScript is that it's a very simple programming language to learn and to use. Many Web publishers who aren't programmers use VBScript to enhance their Web pages.

Learning VBScript

If there was ever a programming language that should have been adopted for use on the Web, it's Visual Basic. Microsoft's Visual Basic is founded on the simplest programming language ever designed, called Basic. Extending the simplicity of Basic to a more structured and modern object-oriented programming approach made Visual Basic a smashing success story. A language that understands objects-like buttons, toolbars, and menus-and is easy to use is a dream come true for programmers.

When the developers at Microsoft redesigned Visual Basic for the Web, they knew they had to get rid of the massive overhead associated with Visual Basic programs. This meant streamlining every aspect of Visual Basic and keeping only the essentials of the language. The developers also knew that security was a key concern for Web programming languages. A Web programming language that opened the end user's system to attack and compromise wouldn't succeed.

To protect the end user's computer, VBScript eliminates the cause of most security problems. For example, VBScript doesn't allow scripts to modify files on the end user's computer in any way. By preventing the reading and writing of files and directories on the end user's computer, VBScript closes the door on most security problems.

Note
Although vbscript couples the best aspects of Visual Basic with a strict security model, it can be used with other Internet technologies, like activex. You will learn all about integrating activex and vbscript in Chapter 33, "Integrating activex and vbscript."

Like most basic programming languages, VBScript is an interpreted language, which is both good news and bad news. The good news is that you don't need to compile your scripts as you would with a program written in C or C++. Your scripts are directly interpreted, line by line, when they're executed in the user's browser. The bad news is that before anyone can run your scripts, he or she needs a VBScript interpreter, which is part of the standard Internet Explorer browser package. It's installed automatically when you install Internet Explorer.

Although Microsoft's Internet Explorer 3.0 and later versions include a VBScript interpreter, most other browsers don't. However, there's an add-on module for Netscape Navigator 3.0/4.0 that supports VBScript. Netscape Navigator users will need to install this add-on module before they can fully use your VBScript-enhanced pages.

Putting VBScript to Work for You

The possible uses for VBScript in your Web pages are endless. You can use scripts to create forms that change in response to users' questions; these customized forms could tailor orders, surveys, and customer support to the customer's needs. The results from VBScript-enhanced forms can be processed locally by the user's browser or can be passed on to a server script for further processing.

VBScript can be used to add interactive menus and buttons to the page. When the user makes a menu selection, portions of the page can change in response to the selection. At the click of a button, a dialog box can open to answer the user's question, offer helpful hints, or prompt the user when errors occur. (See Figure 30.1.)

Figure 30.1 : Using VBScript to display dialog boxes.

To add these graphical objects to your pages, use the basic controls offered by HTML forms. For example, the button shown in the sample page was added with the following line of code:


<INPUT TYPE=BUTTON NAME=cmdButton VALUE="Click Me">

You should recognize the <INPUT> tag from Chapter 27, "Form Creation and Design." As discussed in that chapter, the TYPE attribute is used to set which type of form element to add to the page. Here, the form element is a button-named cmdButton-displayed with the label Click Me.

By combining the form elements you learned about in Chapter 27, you can easily create interactive Web pages complete with buttons, text fields, text areas, radio buttons, and checkboxes. Later in the chapter, you will learn more about adding controlled objects to your VBScript-enhanced pages.

Displaying the dialog box associated with the button was done with the following code:


Sub cmdButton_OnClick



     Msgbox "You will see this dialog box when you click the button inserted

in the sample page. You can close the dialog box by clicking in the OK button."



End Sub

By examining this code, you can see how VBScript works. The name of the button is cmdButton; it has an event related to it called OnClick. When the button is clicked, the subroutine cmdButton_OnClick is automatically executed. VBScript features many ways of automatically handling user events, such as button clicks, mouse movement, and detecting when the pointer is over an object. The Msgbox statement tells the user's browser to display a dialog box with the contents you define between the quotation marks.

Listing 30.1 shows the complete markup for the page shown in Figure 30.1. As you examine Listing 30.1, don't worry about the syntax used to add scripts to your pages; you'll find detailed instructions later in this chapter.


Listing 30.1. Using buttons.

<HTML>

<HEAD>

<TITLE>Adding Buttons &amp; Dialog Boxes with VBScript</TITLE>

</HEAD>



<BODY BGCOLOR="#FFFFFF">

<CENTER>

<H1>Introducing VBScript</H1>

</CENTER>



<P ALIGN="LEFT">Using VBScript, you can add buttons and menus to your pages.

 At the press of a button, a dialog box can appear to answer the user's

 question, offer helpful hints, or prompt the user when errors occur.</P>



<INPUT TYPE=BUTTON NAME=cmdButton VALUE="Click Me">



<SCRIPT LANGUAGE="VBScript">

<!--



' This procedure is executed whenever the button labeled cmbButton is clicked

Sub cmdButton_OnClick



     Msgbox "You will see this dialog box when you click the button inserted

in the sample page. You can close the dialog box by clicking in the Ok button."



End Sub



-->

</SCRIPT>



</BODY>

</HTML>


VBScript is great for crunching numbers, too. You can create a script to perform calculations, such as computing your annual salary based on wages and investment income or determining the time it will take to travel from one city to another.

With CGI, the user would have to fill out a form, submit the form to a server, and then wait for the server to respond. When the server finished the calculations, the results would then be sent back to the client, which would display the results. As you know from earlier discussions on CGI, the results are usually displayed on a separate results page. With VBScript, all this back-and-forth processing is eliminated. The user can fill out a form and see the results instantly-and on the same page!

The sample page shown in Figure 30.2 uses VBScript to compute the sales tax on an order. The user simply enters the appropriate values and clicks a button that causes a script to compute and display the results.

Figure 30.2 : Using VBScript to compute sales tax.

Although the script used to perform the calculation shown in Listing 30.2 is longer than the previous script example, the script has a fairly basic structure. Simply put, the script accepts three values and displays the results after computations are made.


Listing 30.2. Calculating costs and sales tax.

<HTML>

<HEAD>

<TITLE>Using VBScript to Crunch Numbers</TITLE>

<STYLE>

H1  {font: 35pt Times; color: blue}

P  {font: 12pt Times; color: red; text-indent: .5in; margin-right: 1in}

</STYLE>

</HEAD>



<BODY BGCOLOR="#FFFFFF">



<H1>

<IMG SRC="power.jpg" ALIGN=LEFT>

Extreme Sports Hawaii Getaways

<IMG SRC="power.jpg" ALIGN=RIGHT>

</H1>



<BR CLEAR=LEFT><H2>Going to the Extreme on a Budget</H2>



<P>To determine the cost of your getaway, enter the order number of days

you want to stay followed by the number of people in your party.

Residents of Hawaii must pay an additional sales tax of 7%.</P>



<PRE>

      Number of days: <INPUT NAME="tripDays" SIZE=3>

    Number of people: <INPUT NAME="tripSize" SIZE=3>

  State of residence: <INPUT NAME="resState" SIZE=2>

</PRE>



<P><B><INPUT TYPE=BUTTON VALUE="How much to get away from it

all and go to the extreme?" NAME="cmdCost"></B></P>



<PRE>

    Sub Total               $<INPUT NAME="tripCost" SIZE=10>

    Sales Tax (7% HI only)  $<INPUT NAME="tripTax" SIZE=10>



    Total                   $<INPUT NAME="tripTotal" SIZE=10>

</PRE>



<SCRIPT LANGUAGE="VBScript">

<!-- Option Explicit



   Sub cmdCost_OnClick()



Dim State

Dim tripLength

Dim tripParty

Dim Cost

Dim Tax

Dim Total



tripLength = tripDays.Value

tripParty = tripSize.Value

State = resState.Value



If tripLength = 0 Then

    MsgBox "Please enter the length of your getaway."

    Exit Sub

End If

If tripParty = 0 Then

    MsgBox "Please enter the number of people in your party."

    Exit Sub

End If



Cost = 75.00 * tripLength * tripParty



If State = "HI" Then

     Tax = Cost * 0.07

Else

     Tax = 0

End If



Total = Cost + Tax



tripCost.Value = Cost

tripTax.Value = Tax

tripTotal.Value = Total



   End Sub



-->

</SCRIPT>



</BODY>

</HTML>


Getting Ready to Use VBScript

As a VBScript developer, you have an expanded role in Web publishing and may need to modify options in your browser for this new role. Most browsers consider VBScript to be a form of active content. You'll learn about active content and ActiveX in Chapter 31, "Exploring ActiveX and ActiveX Controls." Because running active content can present security concerns, the ability to run scripts is sometimes disabled.

If you're using Internet Explorer 3.0, you can check the security options by choosing Options from the View menu and clicking the Security tab. Figure 30.3 shows the options for the Security tab. Generally, you should select all the available options so you can see active content in any form, whether it's VBScript, JavaScript, Java, or ActiveX.

Figure 30.3 : Setting security options in Internet Explorer 3.0.

You should also check your browser's current safety level setting; to do this, click the button shown in Figure 30.3 labeled Safety Level. By default, Internet Explorer is set to the highest safety level, so scripts with errors or safety problems won't be executed. As a VBScript developer, you should probably set the safety level to Medium, as shown in Figure 30.4, which allows you to execute and view potentially unsafe content.

Figure 30.4 : Choosing a safety level for active content in Internet Explorer 3.0.

Adding Scripts to Your Page

Adding scripts to your Web pages is easy. All you have to do is place the begin tag <SCRIPT> where the script starts and the end tag </SCRIPT> where it ends. The <SCRIPT> tag has one attribute called LANGUAGE, which identifies the scripting language you're using. Since you're creating scripts in VBScript, use the value LANGUAGE="VBScript" to tell this to your browser.

Here's an example of how to add a script to your page:


<HTML>

<HEAD>

<TITLE>Example</TITLE>

</HEAD>

<BODY>



<SCRIPT LANGUAGE="VBScript">



Insert your script here!



</SCRIPT>



</BODY>

</HTML>

Although the most popular browsers available today support scripts, browsers that don't support scripts display your script's code with the contents of your Web page. To avoid this problem, follow the begin script tag with a begin comment tag, and precede the end script tag with an end comment tag. Here's how you can hide the script from non-compatible browsers:


<HTML>

<HEAD>

<TITLE>A Better Example</TITLE>

</HEAD>

<BODY>



<SCRIPT LANGUAGE="VBScript">

<!--



Your script is safely hidden here!

Non-compatible browsers will not display

the script with the contents of the page.



-->

</SCRIPT>



</BODY>

</HTML>

Scripts in pages may be executed as the page loads. If the script refers to objects that aren't downloaded to the browser, there could be problems. To avoid possible conflicts, make your scripts the last element in the page. To do this, insert the script into the page just before the end body tag </BODY>, and place all other markup before the script element, as shown here:


<HTML>

<HEAD>

<TITLE>Placing Scripts in Your Pages</TITLE>

</HEAD>

<BODY>



Insert Markup and Main Contents Here!



<SCRIPT LANGUAGE="VBScript">

<!--

Insert Your Script Here!

-->

</SCRIPT>

</BODY>

</HTML>

VBScript Basics

The syntax and structure of programs written in VBScript are like a familiar shoe for anyone who has programmed before. This is true regardless of which programming language you might have used.

Variables

Creating variables in VBScript is easy-all you need to do is give the variable a name. If you assign a name to a variable, you can later refer to the variable by name in your code. There are two ways to declare variables: explicitly or implicitly.

When you declare an explicit variable, you tell VBScript with the keyword Dim that you're creating a variable, then follow the Dim keyword with the variable name. If you wanted to explicitly declare a variable called eValue, you could use the following:


<SCRIPT LANGUAGE="VBScript">

<!--



Dim eValue



eValue = eValue + 1



-->

</SCRIPT>

When you implicitly declare a variable, you use the variable without first declaring it, so you don't need to use the Dim keyword. VBScript creates the variable for you as necessary. If you wanted to use a variable called iValue implicitly, you could use the following:


<SCRIPT LANGUAGE="VBScript">

<!--



iValue = 150



-->

</SCRIPT>

By default, VBScript allows you to mix implicit and explicit variables in your code. The problem with this is that any variable name is assumed to be valid. For example, if you used a variable called iValue and later assigned a value to a variable called iVale, VBScript would create instances of both variables, even if iVale is a typo for iValue. To avoid this, you can set the Explicit option.

Using the Explicit option forces you to declare all variables explicitly with the Dim keyword and makes sure your variables are valid. This option should immediately follow the begin comment tag, as follows:


<SCRIPT LANGUAGE="VBScript">

<!-- Option Explicit



Your script here.



-->

</SCRIPT>

As most programmers know, normally when you use variables in a program, you must state the type of variable. If the variable is used with integers, you declare the variable as an integer; if the variable is used with strings, you declare the variable as a string. However, typing variables appropriately can lead to problems in code and also creates a complex structure that increases the overhead required for programs.

To avoid problems and streamline VBScript, VBScript automatically allocates a variable type to any variable you use in your programs. Variable types used by VBScript include: Boolean, Byte, Integer, Long, Single, Double, Date, String, Object, Error, Empty, and Null.

Generally, if you use whole numbers, such as 5 or 8, with a variable, VBScript creates the variable as an integer. Variables with values that use decimal points, such as 3.5 or 5.82, are usually assigned as double-precision floating-point values-Doubles. Variables entered with a mixture of alphabetical and numeric characters, such as H2O or 4-H, are created as Strings.

Because VBScript can automatically convert between some variable types, most variable conflicts are eliminated. However, if you try to add a String variable to a numeric variable type, you will get an error, so if a variable has alphanumeric characters, don't try to perform numeric calculations with it.

Note
Before performing calculations, you can make sure variables are numeric by using the IsNumeric function. This function returns a value of true if the variable is numeric and false if it isn't. This sample code checks for a numeric variable:
If IsNumeric(Value1) = True Then
    Value2 = Value1 + 5
These related functions check other variable types: IsDate, IsEmpty, IsNull, IsNumeric, and IsObject.

Arrays

Arrays allow you to group related sets of data together. When you create an array, you must specify its number of dimensions. VBScript allows you to create arrays with up to 60 dimensions. A one-dimensional array is like a column of tabular data; a two-dimensional array is like a spreadsheet with rows and columns; and a three-dimensional array is like a 3D grid that takes time and space into account.

You could create a one-dimensional array from a single column of tabular data. If there were 20 data points in the column, you could declare the array as follows:


Dim myArray(19)

Note
Arrays always begin at 0 and end at the number of data points in the array minus 1. Therefore, an array with 20 data points is initialized as Array_Name(19).

You could create a multi-dimensional array from the cells of a spreadsheet. If the spreadsheet has three columns, each with five rows of data points, you could declare the array as follows:


Dim myArray(2,4)

If you want to get the value of a specific cell in the spreadsheet, you could use the following:


myValue = Array_Name(columns -1, rows -1)

In this statement, columns is the column position of the cell, and rows is the row position of the cell, so if you want to know the value of the cell in column 1, row 4, you could use the following:


myValue = myArray(0,3)

Although these sample arrays have fixed sizes, you can also size arrays dynamically. This allows you to use input from users to drive the size of the array. Here's how to declare a dynamic array:


Dim dynamicArray()

Later you can tell VBScript the size of the array by using the ReDim function in one of these two ways:


ReDim dynamicArray(iCount - 1)

ReDim dynamicArray(columnCount - 1, rowCount - 1)

Note
Once you create an array at a specific dimension, you can't change the dimension. This means that if you create a two-dimensional array, you can't change it later to a three-dimensional array.

To determine the size of an array at any time, you can use the UBound function, which returns the array's upper boundary. The following sample returns the upper boundary of the array in a message box:


Dim myArray(99)

Dim x

For x = 0 to UBound(myArray)

     myArray(x) = "Initial"

Next

Msgbox "The upper boundary of the array is" & UBound(myArray)

Arithmetic Operators

You perform calculations in VBScript in much the same way as you write out calculations longhand. The only difference is that you usually assign the result to a variable.

To add numbers, use the + operator, as shown in these two examples:


Result = 1 + 5

Result = ValueA + ValueB

To subtract numbers, use the - operator, as these two examples show:


Result = 5 - 1

Result = ValueB - ValueA

To multiply numbers, use the * operator; here are two examples of how to do that:


Result = 2 * 4

Result = ValueA * ValueB

To divide numbers, use the / or \ operator, as shown in the following examples:


Result = 2 / 4

Result = ValueA / ValueB

In division, you often have a remainder. Since you might want to perform calculations based on the remainder, you need a way to determine it. In VBScript, you do this by using the Mod function. For the following expression, the value of the result is set to 1:


Result = 7 Mod 2

To multiply by an exponent, use the ^ operator. This example is the same as 3 * 3 * 3 * 3:


Result = 3 ^ 4

You can also use this example, which is the same as ValueC * ValueC:


Result = ValueC ^ 2

You can negate a value by using the - operator, as shown in these two examples:


Result = -2 * 3

Result = -ValueA * ValueB

When you mix operators, VBScript performs calculations using the same precedence order your math teacher taught you. For example, multiplication and division in equations are carried out before subtraction and addition, as shown in these examples:

3 + 2 * 6 = 15
2 / 2 + 3 = 4

The complete precedence order of operators is shown in Table 30.1. According to the table, exponents have the highest precedence order and are always calculated first.

Table 30.1. The precedence order of arithmetic operations.

Order
Operation
1
Exponents (^)
2
Negation (-)
3
Multiplication (*) and Division (/)
4
Remainders (Mod)
5
Addition (+) and Subtraction (-)

Comparison Operators

When you perform comparisons, you check for certain conditions, such as "Is A equal to B?" To perform comparisons in VBScript, you use a set of comparison operators that aren't much different from the comparison operators used in math every day. The only difference is that in your scripts, you typically use a control flow, such as conditional looping, with your comparison. For example, if A is equal to B, then you will perform a specific task; if A is not equal to B, then you will perform a different task.

To see whether a variable is equal to another variable or to a specific value, use the equal sign. Here's an example that checks for equality:


if myValue = 0 Then

   Msgbox "The variable is set to zero."

if myValue = Input Then

   Msgbox "The values are equal."

To see whether variables aren't equal, use the inequality operator, as shown in this example:


if myValue <>0 Then

   Msgbox "The variable is NOT set to zero."

if myValue <>Input Then

   Msgbox "The values are NOT equal."

To check whether one variable is less than or greater than another variable, use the less than and greater than operators. You can check for values greater than or less than a variable as follows:


if myValue < 0 Then

   Msgbox "The value is less than zero."

if myValue > 0 Then

   Msgbox "The value is greater than zero."

Another type of comparison you can perform is to see whether a variable is less than or equal to a value. Likewise, you can see whether a variable is greater than or equal to a value. Here is an example of this type of comparison:


if myValue <= Input Then

   Msgbox "myValue is less than or equal to Input."

if myValue >= 0 Then

   Msgbox "The value is greater than or equal to zero."


Note
There is no set precedence order for comparison operators. Comparisons are always performed from left to right.

When you compare objects, such as buttons, you use a special comparison operator called Is. By using the Is operator, you can see whether two objects are equivalent. The operator returns a result that is true if the objects are equivalent, or false if they aren't. This example shows how you can check whether the object reference cmd_Button refers to the object Button:


Result = cmd_Button Is Button

If Result = True Then

    Msgbox "The objects are equivalent."

Else

Msgbox "The objects are NOT equivalent."

You can also perform the comparison directly in the control flow statement:


If cmd_Button Is Button Then

    Msgbox "The objects are equivalent."

Else

        Msgbox "The objects are NOT equivalent."

Strings

Strings are sets of alphabetical and numeric characters. In VBScript, there are many ways to use strings. Because VBScript automatically types variables for you, you don't need to declare a variable as a string. You can declare a variable this way:


Dim aString

Then later you can define a string value for the variable:


aString = "This is a String."

Often, you want to add strings together. For example, if a user enters his or her full name as three separate variables representing the first, middle, and last name, you might want to add these strings together. Although you may see scripts that use the + operator to concatenate strings, the normal operator for string concatenation is the & operator. With the & operator, you can add strings together as follows:


fullName = firstName & " " & Middle & " " & lastName

Sometimes you also want to display the value of a string in a message box. To do this, use the & operator, as shown in the following sample code:


bString = "Cool"

Msgbox "The value of the string is: " & bString

This code displays a dialog box with the following message:


The value of the string is: Cool

Comments

Just as you can add comments to HTML markup, you can add comments to your VBScript code. To add comments, use the single quotation mark. All text after the single quotation mark and on the same line is interpreted as a comment. Here are some examples of using comments in your code:


'This variable holds the first name of the customer

Dim firstName

'This variable holds the middle name of the customer

Dim Middle

'This variable holds the last name of the customer

Dim lastName

Control Flow with Conditionals

In much the same way as traffic lights control the flow of traffic on the street, conditional instructions control the flow of instructions in your code.

If…then

If you want to execute a set of instructions only when a certain condition is met, you can use an If…then condition. You can control the execution of instructions based on a true condition, as follows:


if condition = True Then

  A = B

End If

An If…then condition can also be used in this way:


if condition Then

  A = B

End If

You can control the execution of instructions based on a false condition, as follows:


if condition = False Then

  A <> B

End If

You can also use this form:


if Not condition  Then

  A <> B

End If

You can extend the If…then condition with the Else and ElseIf statements. The Else statement offers an alternative when a condition you specified isn't met. Here's the structure of an if…then…else condition:


if homeRun = True Then

    Msgbox "The condition has been met."

Else

    Msgbox "The condition has not been met."

End If

To add more conditions, you can use the ElseIf statement. In this way, each condition you add to the code is checked for validity. Here's an example that uses the ElseIf statement:


if firstValue < 0 Then

  Msgbox "The value is less than zero."

ElseIf firstValue = 0 Then

  Msgbox "The value is equal to zero."

ElseIf firstValue = 1 Then

  Msgbox "The value is equal to one."

ElseIf firstValue = 2 Then

  Msgbox "The value is equal to two."

ElseIf firstValue = 3 Then

  Msgbox "The value is equal to three."

ElseIf firstValue = 4 Then

  Msgbox "The value is equal to four."

Else

  Msgbox "The value is greater than 4."

End If

Select Case

Checking for multiple conditions with the ElseIf structure can be tedious. When you want to check more than three conditions, you should probably use the Select Case statement. In the Select Case structure, the last example in the previous section can be transformed into code that's clearer and easier to understand:


Select Case firstValue

   Case < 0

     Msgbox "The value is less than zero."

   Case 0

     Msgbox "The value is equal to zero."

   Case 1

     Msgbox "The value is equal to one."

   Case 2

     Msgbox "The value is equal to two."

   Case 3

     Msgbox "The value is equal to three."

   Case 4

     Msgbox "The value is equal to four."

   Case Else

     Msgbox "The value is greater than 4."

End Select

If you compare the ElseIf example and the Select Case example, you can see that the Select Case example requires less code and has a simpler structure. You can apply this same structure any time you want to check for multiple conditions. Here's another example of Select Case:


Select Case Abbrev

   Case "HTML"

     Message "The HyperText Markup Language."

   Case "SGML"

     Message "The Standard Generalized Markup Language."

   Case "VRML"

     Message "The Virtual Reality Modeling Language."

   Case Else

     Message "You have entered an abbreviation not known to the system."

End Select

Control Flow with Looping

Sometimes you want to repeatedly execute a section of code. In VBScript, there are three ways you can do this:

For…Next

To execute a code segment for a specific count, use For…Next looping. The structure of For…Next is as follows:


For Counter = Start to Finish

   insert code to repeat

Next

Using For…Next looping in your code is easy. The following example uses this structure to initialize an array of 20 elements:


For x = 0 to 19

   aStruct(x) = "Unknown"

Next

After the For…Next loop is executed, all 20 elements in the array are initialized to the value Unknown. To make the For…Next loop more versatile, you can step through the counter at specific intervals. To do this, follow the Step keyword with a positive or negative value. The following example sets the array positions 0, 2, 4, 6, and 8 to Even:


For x = 0 to 8 Step 2

   aStruct(x) = "Even"

Next

This loop sets the array positions 3, 6, and 9 to Multiple.


For x = 3 to 9 Step 3

   aStruct(x) = "Multiple"

Next

When you use a negative step value, you should reverse the normal order of the counter. Therefore, instead of going from the lowest value to the highest value, you go from highest to lowest:


For x = 8 to 0 Step -2

   aStruct(x) = "Even"

Next



For x = 9 to 3 Step -3

   aStruct(x) = "Multiple"

Next

Do While

To execute a code segment while a condition is met, use Do While looping. The structure of this loop is as follows:


Do While condition

   insert code to repeat

Loop

As long as the condition is met, the loop is executed. To break out of the loop, you must change the condition at some point within the loop. Here's an example of a Do While loop that changes the status of the condition:


Do While homeRun = True



   If basesLoaded Then

      Message "Great time to hit a home run."

   ElseIf Balls = 3 And Strikes = 2 Then

      Message "Go for it!"

   Else

      homeRun = False

   EndIf



Loop

By placing your condition at the top of the loop, you make sure the loop is executed only if the condition is met. Sometimes you want to execute the loop at least once before you check the condition; to do this, you can place the check for the condition at the bottom of the loop, as shown in this example:


Do



   If basesLoaded Then

      Message "Great time to hit a home run."

   ElseIf Balls = 3 And Strikes = 2 Then

      Message "Go for it!"

   Else

      homeRun = False

   EndIf



Loop While homeRun = True

Do Until

If you want to execute a loop until a condition is met instead of while a condition is met, use Do Until looping, as shown in this example:


Do Until condition

    Insert code to repeat

Loop

To make sure the loop is executed at least once, you can use the following structure:


Do

    Insert code to repeat

Loop Until condition

Here's another example of a Do Until loop:


Do



   If basesLoaded Then

      Message "Great time to hit a home run."

   ElseIf Balls = 3 And Strikes = 2 Then

      Message "Go for it!"

   Else

      homeRun = False

   EndIf



Loop Until homeRun = True

Note
If you compare the Do While loops in the previous section to the Do Until loops in this section, you can see that the logic for both types of loops is similar. The key difference is in how the logic is applied. In a Do While loop, you execute code while a condition is met; in a Do Until loop, you execute code until a condition is met.

Going Beyond the Basics with VBScript

As you've seen in the previous section, programming with VBScript is fairly straightforward. To go beyond the basics, take a look at how to group sections of code into procedures.

Basic Procedure Classes

Procedures you create in VBScript are groups of statements that perform a particular task. After creating a procedure, you can call it from different locations in your code. When the procedure finishes executing, control returns to the code that called the procedure and your script continues executing from there.

The two basic classes of procedures are these:

Functions

Functions-procedures that return a value to the statement that called them-are very useful in your scripts. When you create a function, you can define parameters required to execute the function. Parameters are optional variables that you can use to pass values to the function.

Here is the basic structure of a function:


Function functionName(argument1, argument2, ..., argumentN)

   Insert function code here.

End Function

You can use functions in your code as follows:


Function getName

   Dim goodName

   Do While goodName = ""

      goodName = InputBox "Enter your full name:"

   Loop

   getName = goodName

End Function

In the example, getName is the name of the function. Because the function accepts no parameters, none are defined after the function name. A temporary variable called goodName is created to make the code easier to follow and debug. The temporary variable is used to store the user's input. Once the user enters a valid name, the Do While loop is exited. The value the user entered is assigned to the function, allowing the value to be returned to the calling statement.

Caution
Variables used within functions or subroutines are temporary variables. These variables exist only within the scope of your function or subroutine, so local variables are another name for variables used within procedures.

You can call a function in one of these two ways:


Call getName()

fullName = getName()

Another way to call a function is within a statement:


Msgbox "The name you entered is: " getName()

When there are no parameters to pass to the function, the parentheses are optional:


fullName = getName

To better understand how parameters are used, try creating a function that converts a time entry to seconds. This function, called countDays, accepts four parameters: nYears, nDays, nHours, and nMinutes. Because these parameters are passed directly to the function, you don't need to create temporary variables in the function. The code for the function countSeconds is as follows:


Function countSeconds(nYears, nDays, nHours, nMinutes)

   Dim tempSeconds

   tempSeconds = ((365 * nYears + nDays) * 24 + nHours) * 3600 + 60 * nMinutes

   countSeconds = tempSecounds

End Function

When you call this function, the parameters are mandatory and must be entered in the order defined. Here's a statement that calls the countSeconds function:


numSeconds = countSeconds(1,69,24,5)

Note
You can break out of a function and return to the caller at any time by using the Exit Function statement. This statement is useful when a predetermined condition has been met and you want to return to the calling statement without finishing the function's execution.

Subroutines

You can also use subroutines in your scripts. A subroutine is a procedure that can be called anywhere in the code but doesn't return a value to the caller. You can pass parameters to a subroutine just as you do to a function.

The structure of a subroutine is almost identical to the structure of a function:


Sub subroutineName(argument1, argument2, ..., argumentN)

   Insert subroutine code here.

End Sub

You can use subroutines in your code as follows:


Sub displayError(errorMessage)

   MsgBox "Error: " & errorMessage

End Sub

In the example, displayError is the name of the subroutine. The subroutine expects one parameter to be passed to it; this parameter holds the error message to display to the user.

You could call the displayError subroutine in one of these two ways:


Call displayError("You have entered an invalid message.")

displayError("You have entered an invalid message.")

When there are no parameters to pass to the subroutine, the parentheses are optional:


Call displayWarning

Note
You can break out of a subroutine and return to the caller at any time by using the Exit Sub statement. When you use this statement, control is returned to the calling statement without finishing the subroutine's execution.

System Procedure Classes

Beyond the basic procedure classes are system classes. There are two system classes for procedures: events and methods.

Events

An event is a subroutine executed automatically by the system when a certain condition exists. There are events for mouse clicks, mouse movements, button clicks, and so on. You refer to events with a control name and an event name, separated by the underscore character, such as this:


myButton_OnClick

The control name is myButton, and OnClick is the event name.

Here is an event that's automatically executed when a button labeled cmdButton is clicked:


Sub cmdButton_OnClick



     Msgbox "You will see this dialog box when you click the button inserted

in the sample page. You can close the dialog box by clicking in the OK button."



End Sub

OnClick is certainly one of the most used events, but it's not the only event you can use. Other events you can use and their meanings are shown in Table 30.2. In the next chapter, you will see events used with HTML controls.

Table 30.2. Event procedures and their uses.

Event NameUse
OnBlur Automatically executed when an object is deselected
OnChange Automatically executed when a user changes the object by making a selection
OnClick Automatically executed when an object, such as a button, is clicked
OnFocus Automatically executed when an object is active, such as when the user selects it

Methods

Just as subroutines and functions are very similar, so are events and methods. Methods are normally used to cause events to occur in the code, rather than as a result of interaction with the user. Therefore, a method is a controlled event. Unlike normal events, controlled events aren't executed automatically.

Although you can call a method, you must refer to it by the object to which it relates. To call a method, use the following syntax:


objectName.methodName

objectName is the name of the object you're referring to, and methodName is the name of the method you want to execute.

One way to use a method is be to simulate button presses during a product tutorial. Instead of the user driving the event, you would simulate the event to trigger an identical response. Following this, you could execute this event


Sub myButton_OnClick



     Msgbox "You will see this dialog box when you click the button inserted

in the sample page. You can close the dialog box by clicking in the OK button."



End Sub

with the following code:


myButton.Click

Figure 30.5 shows a sample page with a button control. When the button is clicked, two things happen:

Figure 30.5 : An example of a button control.

Examine the source code shown in Listing 30.3 to see the counter assignment and the method call. In the next chapter, you'll see many examples of method calls in scripts.


Listing 30.3. A script with a method call.

<HTML>

<HEAD>

<TITLE>Fun With Button Controls</TITLE>

<STYLE>

H2  {font: 40pt Times; color: red}

P  {font: 12pt Times; color: blue; text-indent: .5in; margin-right: 1in}

</STYLE>

</HEAD>



<BODY>

<H2>Using Button Controls</H2>

<P>Button are one of the coolest controls to add to your page. You can add

 a button control anywhere in your page. Using button controls, you can

 boost the fun-level of your pages dramatically. Every time the user clicks

 on the button on this page, the counter increases.</P>

<CENTER>

<INPUT TYPE=BUTTON VALUE="Click Me" NAME="funButton">

</CENTER>



<HR SIZE=10 NOSHADE>



<SCRIPT LANGUAGE="VBScript">

<!--  Option Explicit



Dim Counter



Sub funButton_OnClick()

     Counter = Counter + 1

     funButton.Value = Counter

End Sub



-->

</SCRIPT>

</BODY>

</HTML>


Fun with Message Boxes

Message boxes are used to display information to users. VBScript offers many ways to add pizazz to message boxes. To display a message box, simply add this statement:


Msgbox "The message you want to display."

Note
Alert boxes are a special type of message box and can be used to display error messages, cautions, and warnings. To display an alert box, use the Alert function as follows:
Alert "The error, caution, or warning to display."

You can customize message boxes with titles, icons, and several button styles. To add these elements to your message boxes, you must use the following syntax:


Msgbox "The message to display", buttonType + iconType, _

        "Title for message box", helpFile, helpFileContext

Buttons for Message Boxes

The OK button is the default button for all message boxes, but there's a whole host of useful buttons, including Yes, No, Cancel, Retry, Ignore, and Abort. To add your own buttons to a message box, you must do two things:

Here's how you would add Yes and No buttons to a message box:


dim vbYesNoCancel: vbYesNoCancel = 3

Msgbox "The message to display.", vbYesNoCancel

vbYesNoCancel are the button types you want to add, and 3 is the parameter value.

A message box with the Yes, No, and Cancel buttons is shown in Figure 30.6. The markup and source code for the page is shown in Listing 30.4.

Figure 30.6 : Making your message boxes more useful with buttons.


Listing 30.4. Adding buttons to message boxes.

<HTML>

<HEAD>

<TITLE>Adding Buttons to Your Message Boxes</TITLE>

<STYLE>

H2  {font: 40pt Times; color: blue}

P  {font: 12pt Times; color: gray; text-indent: .5in; margin-right: 1in}

</STYLE>

</HEAD>



<BODY BGCOLOR="#FFFFFF">

<H2>Using Unique Buttons</H2>

<P>The OK button is the default button for all message boxes. To specify

 buttons, you must pass the second parameter to the function call. When

 you add buttons, you normally add them in specific combinations, such

 as a Yes button with a No button.</P>

<CENTER>

<INPUT TYPE=BUTTON VALUE="Display Message Box" NAME="displayButton">

</CENTER>



<HR SIZE=10>



<SCRIPT LANGUAGE="VBScript">

<!--



dim vbYesNoCancel: vbYesNoCancel = 3



Sub displayButton_OnClick

     Msgbox "Do you want to try again?", vbYesNoCancel

End Sub



-->

</SCRIPT>

</BODY>

</HTML>


When you add buttons, you normally add them in specific combinations, such as a Yes button with a No button. The available button combinations and their associated values are summarized in Table 30.3.

Table 30.3. Buttons for message boxes.

Parameter NamePurpose
Value
vbOk Shows the OK button
0
vbOkCancel Shows OK and Cancel buttons
1
vbAbortRetryIgnore Shows Abort, Retry, and Ignore buttons
2
vbYesNoCancel Shows Yes, No, and Cancel buttons
3
vbYesNo Shows Yes and No buttons
4
vbRetryCancel Shows Retry and Cancel buttons
5

Icons for Message Boxes

Adding a unique icon to a message box is easy. Just remember that buttons and icons are part of the same parameter, which is why you use the plus sign to separate the button types from the icon type. To add icons to a message box, you must do two things:

Here's an example of a message box with an icon:


Dim vbRetryCancel: vbRetryCancel=5

Dim vbInformation: vbInformation=64

Msgbox "The message to display.", vbRetryCancel + vbInformation

A message box with an information icon is shown in Figure 30.7, and the source for the page is shown in Listing 30.5.

Figure 30.7 : Adding icons to message boxes.


Listing 30.5. Adding icons to message boxes.

<HTML>

<HEAD>

<TITLE>Adding Icons to Your Message Boxes</TITLE>

<STYLE>

H2  {font: 40pt Times; color: blue}

P  {font: 12pt Times; color: gray; text-indent: .5in; margin-right: 1in}

</STYLE>

</HEAD>



<BODY BGCOLOR="#FFFFFF">

<H2>Using Icons</H2>

<P>Adding a unique icon to a message box is easy. Just remember that buttons

 and icons are part of the same parameter, which is why you use the plus sign

 to separate the button types from the icon type.</P>

<CENTER>

<INPUT TYPE=BUTTON VALUE="Display Message Box" NAME="displayButton">

</CENTER>



<HR SIZE=10>



<SCRIPT LANGUAGE="VBScript">

<!--



Dim vbRetryCancel: vbRetryCancel=5

Dim vbInformation: vbInformation=64



Sub displayButton_OnClick

     Msgbox "This option allows you to compute averages. If you want to see" & _

    "the calculator compute averages, click on the Retry button.", _

     vbRetryCancel + vbInformation

End Sub



-->

</SCRIPT>

</BODY>

</HTML>


The complete list of icons you can add to your message boxes is shown in Table 30.4.

Table 30.4. Icons for message boxes.

Parameter Name
Value
Purpose
vbCritical
16
Shows an icon with an ¥, used for critical errors
vbQuestion
32
Shows an icon with a question mark, used for questions
vbExclamation
48
Shows an icon with an exclamation point, used for minor errors, cautions, and warnings
VbInformation
64
Shows an icon with an I, used for informational messages

Titles for Message Boxes

You can easily add descriptive titles to your message boxes. (See Figure 30.8.) All you need to do is to specify the title in the third parameter passed to the Msgbox function call. Here's an example of a message box with a descriptive title:

Figure 30.8 : Adding titles to your message boxes.


Msgbox "You have made an error. Do you want to try again?", _

       vbAbortRetryIgnore + vbExclamation, "Error in Entry: Improper Format"

Listing 30.6 shows the contents of the sample page.


Listing 30.6. Using message box titles.

<HTML>

<HEAD>

<TITLE>Titles for Your Message Boxes</TITLE>

<STYLE>

H2  {font: 40pt Times; color: blue}

P  {font: 12pt Times; color: gray; text-indent: .5in; margin-right: 1in}

</STYLE>

</HEAD>



<BODY BGCOLOR="#FFFFFF">

<H2>Adding Titles</H2>

<P>You can easily add descriptive titles to your message boxes.

 All you need to do is to specify the title in the third parameter

 passed to the Msgbox function call. </P>

<CENTER>

<INPUT TYPE=BUTTON VALUE="Display Dialog" NAME="displayButton">

</CENTER>



<HR SIZE=10 NOSHADE>



<SCRIPT LANGUAGE="VBScript">

<!--



Dim vbAbortRetryIgnore: vbAbortRetryIgnore=2

Dim vbExclamation: vbExclamation=48



Sub displayButton_OnClick

Msgbox "You have made an error. Do you want to try again?", _

       vbAbortRetryIgnore + vbExclamation, "Error in Entry: Improper Format"

End Sub



-->

</SCRIPT>

</BODY>

</HTML>


Using Help Files with Message Boxes

When you use the help parameters, the message box is displayed with a Help button that calls the designated help file when it's clicked. Using the help file context parameter, you can identify a specific topic in the help file to be displayed. Once you designate a help file, the Help button is automatically added to the message box. Users can open the help file by clicking the Help button or pressing the f1 key.

Evaluating Button Clicks in Message Boxes

When you give the user several options, such as Yes/No or Abort/Retry/Ignore, you need to know what button the user selected. Because message boxes return a status code, you can easily evaluate button clicks. All you need to do is assign the message box call to a variable, then evaluate the variable.

Because you're using a procedure call to make the evaluation, the syntax for the message box changes slightly, as shown here:


evaluateButtonClick = Msgbox ("The message to display", buttonType + iconType, _

        "Title for message box", helpFile, helpFileContext)

Anytime this line of code is inserted in a script, a message box is displayed; when the user clicks a button, the returned status code is stored in the variable:


tryAgain = Msgbox ("Do you want to try again?", vbYesNoCancel)

Once you assign a variable to store the returned status code, you can use an If…then or Select Case structure to perform actions in response to the button click. Table 30.5 lists message box buttons and the status codes returned when they're clicked.

Table 30.5. Status codes for message box buttons.

ButtonParameter Name
Status Code
OKvbOk
1
CancelvbCancel
2
AbortvbAbort
3
RetryvbRetry
4
IgnorevbIgnore
5
YesvbYes
6
NovbNo
7

A script that evaluates button clicks in message boxes and then directs the result to a text control is shown in Figure 30.9. To see how this was done, examine the source for this page in Listing 30.7. Although the example uses an If…then loop to evaluate the button click, you could just as easily use a Select Case structure.

Figure 30.9 : Evaluating button clicks in message boxes.

Note
Text controls are just one of many HTML controls you can add to VBScript-enhanced Web pages. You will learn about these controls in Chapter 32, "Using VBScript to Enhance Your Web Pages."


Listing 30.7. Determining button clicks.

<HTML>

<HEAD>

<TITLE>Evaluating Button Clicks In Message Boxes</TITLE>

<STYLE>

H2  {font: 40pt Times; color: blue}

P  {font: 12pt Times; color: gray; text-indent: .5in; margin-right: 1in}

</STYLE>

</HEAD>



<BODY BGCOLOR="#FFFFFF">

<H2>Button Clicks In Message Boxes</H2>

<P>When you present the user with multiple options, such as Yes/No or

 Abort/Retry/Ignore, you need to know what button the user selected.

 Because message boxes return a status code, you can easily evaluate

 button clicks. All you need to do is assign the message box call to

 a variable and then evaluate the variable.</P>



<FORM NAME="coolForm">

<P><INPUT TYPE=BUTTON VALUE="Display Dialog" NAME="displayButton"></P>

<P>Button Evaluation: <INPUT TYPE=TEXT NAME="textControl" SIZE=50 MAXLENGTH=50></P>

</FORM>

<HR SIZE=10 NOSHADE>



<SCRIPT LANGUAGE="VBScript">

<!--



Dim vbYesNoCancel: vbYesNoCancel=3

Dim vbExclamation: vbExclamation=48

Dim vbYes: vbYes=6

Dim vbNo: vbNo=7

Dim vbCancel: vbCancel=2

Dim form

Set form = document.coolForm



Sub displayButton_OnClick

tryAgain = Msgbox ("Do you want to try again?", vbYesNoCancel)



If tryAgain = vbYes Then

     form.textControl.Value = "You clicked on the Yes button."

ElseIf tryAgain = vbNo Then

     form.textControl.Value = "You clicked on the No button."

Else

     form.textControl.Value = "You clicked on the Cancel button."

End If



End Sub



-->

</SCRIPT>

</BODY>

</HTML>


Summary

VBScript is a powerful tool for enhancing your Web pages. Because it's so easy to use, learning VBScript basics, such as how to perform calculations or how to concatenate strings, is a snap. These basic concepts are the building blocks to more advanced subjects such as controlling the flow through your scripts and creating procedures.

Once you understand procedures, you're ready to add interactivity to your pages. One way to do this is with message boxes. There are many uses for message boxes in your scripts, especially if you create "intelligent" message boxes that react to button clicks.