by William Robert Stanek
Microsofts 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; theres 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 Microsofts Visual Basic, your scripts resemble programs written in Visual Basic. If you arent a programmer,
dont worry. The wonderful thing about VBScript is that its a very simple programming language to learn and to use. Many Web publishers who arent programmers use VBScript to enhance their Web pages.
If there was ever a programming language that should have been adopted for use on the Web, its Visual Basic. Microsofts 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 objectssuch as buttons, toolbars, and menusand 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 is a key concern for Web programming languages. A Web programming language that opens the end users system to attack and compromise wouldnt succeed.
To protect the end users computer, VBScript eliminates the cause of most security problems. For example, VBScript doesnt allow scripts to modify files on the end users computer in any way. By preventing the reading and writing of
files and directories on the end users 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, such as ActiveX. You will learn all about integrating ActiveX and VBScript in Chapter 29, "Creating Interactive Pages with Controls."
Like most basic programming languages, VBScript is an interpreted language, which is both good news and bad news. The good news is that you dont 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 theyre executed in the users 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.
Its installed automatically when you install Internet Explorer.
Although Microsofts Internet Explorer 3.0 and later versions include a VBScript interpreter, most other browsers dont. However, theres 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.
Step by step, the next sections introduce VBScript programming. By learning the basics of VBScript programming, you will be ready for the advanced VBScript topics youll find in later chapters such as Chapter 29. After you learn about VBScript,
youll be ready to learn how to use one of FrontPages most advanced featuresthe Scripting Wizard. With the Scripting Wizard, you can generate scripts automatically. You do not need to know VBScript to use Scripting Wizard. However, you
will better understand how to generate scripts automatically if you know how VBScript works. The Scripting Wizard is discussed in Chapter 29 as well.
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 customers needs.
The results from VBScript-enhanced forms can be processed locally by the users 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 users
question, offer helpful hints, or prompt the user when errors occur (see Figure 27.1).
Figure 27.1. Using VBScript to display dialog boxes.
To add these graphical objects to your pages, you will use the basic controls offered by HTML forms. In the example, the form element is a buttonnamed cmdButtondisplayed with the label Click Me.
By combining the form elements you learned about in Chapter 12, "Using Forms and the Form Page Wizard," 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 is accomplished 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 executed automatically. 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 users browser to display a dialog box with the contents you define between the quotation marks.
NOTE
VBScript is not case-sensitive. This means that cmdButton, cmdbutton, and CMDBUTTON all refer to the same subroutine.
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 instantlyand on the same page!
The sample page shown in Figure 27.2 uses VBScript to compute the sales tax on an order. The user simply enters the appropriate values and clicks a button which causes a script to compute and display the results.
Figure 27.2. Using VBScript to compute sales tax.
Although the script used to perform the calculation shown in Listing 27.1 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. If all this seems Greek, dont worry. Later sections go into great detail about writing scripts.
Listing 27.1. Calculating costs and sales tax.
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
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. Youll learn about active content and ActiveX in
Chapter 28, "Exploring ActiveX and ActiveX Controls." Because running active content can present security concerns, the ability to run scripts is sometimes disabled.
If youre using Internet Explorer 3.0, you can check the security options by choosing View| Options and clicking the Security tab. Figure 27.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 its VBScript, JavaScript, Java, or ActiveX.
Figure 27.3. Setting security options in Internet Explorer 3.0.
You should also check your browsers current safety level setting; to do this, click the button shown in Figure 27.3 labeled Safety Level. By default, Internet Explorer is set to the highest safety level, so scripts with errors or safety problems
wont be executed. As a VBScript developer, you should probably set the safety level to Medium, as shown in Figure 27.4, which allows you to execute and view potentially unsafe content.
Figure 27.4. Choosing a safety level for active content in Internet Explorer 3.0.
Just as you use the FrontPage Editor to create pages, you will use the FrontPage Editor to create pages with scripts. Start by opening an existing Web page or creating a new page to which you want to add a script, then move the insertion point to where
you want the script to run. Generally, you will want to place scripts wherever you will use them to add content or updates to the page.
After you have determined where you want to add a script, select Insert|Script from the menu. This opens the dialog box you see in Figure 27.5. In the Language area of the dialog box, select the
checkbox labeled Visual Basic Script. This sets a property that tells the readers browser you are using the VBScript language. For now, enter your scripts directly in the input area provided. When you are finished, click on the OK button.
Figure 27.5. Using the Script dialog box to create scripts.
NOTE
To start the Scripting Wizard, all you have to do is click on the Scripting Wizard button in the Script dialog box. In Chapter 29, you will learn how to use the Scripting Wizard.
So you can easily access your script, the FrontPage Editor adds an icon to your page where the script resides. For VBScript, this icon depicts green, yellow, and red flow chart symbols in front of a document symbol. Double-clicking on this icon opens
the Script dialog box, with your script ready for editing.
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.
Creating variables in VBScript is easyall 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 youre creating a variable, then follow the Dim keyword with the variable name. If you want to explicitly
declare a variable called eValue, you could use the following:
Dim eValue eValue = eValue + 1
When you implicitly declare a variable, you use the variable without first declaring it, so you dont need to use the Dim keyword. VBScript creates the variable for you as necessary. If you want to use a variable
called iValue implicitly, you could use the following:
iValue = 150
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 be the first element in your script:
Option Explicit Your script here.
As most programmers know, when you use variables in a program, you typically 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 variables 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 valuesDoubles. 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, dont 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 isnt. This sample code checks for a numeric variable: If IsNumeric(Value1) = True Then Value2 = Value1 + 5A set of related functions checks other variable types: IsDate, IsEmpty, IsNull, IsNumeric, and IsObject.
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. Heres 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
After you create an array at a specific dimension, you cant change the dimensions. This means that if you create a two-dimensional array, you cant 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 arrays 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)
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. Because 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 27.1. According to the table, exponents have the highest precedence order and are always calculated first.
Order | Operation |
1 | Exponents (^) |
2 | Negation (-) |
3 | Multiplication (*) and Division (/) |
4 | Remainders (Mod) |
5 | Addition (+) and Subtraction (-) |
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 arent 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. Heres 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 arent 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 arent. 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 are sets of alphabetical and numeric characters. In VBScript, there are many ways to use strings. Because VBScript automatically types variables for you, you dont 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
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
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 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 specify isnt met. Heres 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 additional condition you add to the code is checked for validity. Heres 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
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 thats 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. Heres 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
Sometimes you want to repeatedly execute a section of code. In VBScript, there are three ways you can do this:
The sections that follow examine how to use these control flow elements.
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
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. Heres 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
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
Heres 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.
As youve 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.
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:
Functionsprocedures that return a value to the statement that called themare 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 users input. After 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 dont 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. Heres 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 functions execution.
You can also use subroutines in your scripts. A subroutine is a procedure that can be called anywhere in the code but doesnt 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 subroutines execution.
Beyond the basic procedure classes are system classes. There are two system classes for procedures: events and methods.
An event is a subroutine executed automatically by the system when a certain condition exists. There are events for mouse clicks, mouse movements, clicks of buttons, 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 thats executed automatically 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 its not the only event you can use. Other events you can use and their meanings are shown in Table 27.2. In the next chapter, you will see events used with HTML
controls.
Event Name | Use |
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 |
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
user-driven events, controlled events arent 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 youre referring to, and methodName is the name of the method you want to execute.
One way to use a method is 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
By combining form elements with a script, you can easily create highly interactive Web pages. Figure 27.6 shows a sample page with a button control. When the button is clicked, two things happen:
Figure 27.6. A page with an HTML Control.
The push button is added to the page by selecting Push button on the Forms toolbar. In the Button Type area, select the radio button labeled Normal. Next, the properties for the push button are edited so that the Name field
is set to funButton and the Value field is set to Click Me. Click on the OK button to close the Push Button Properties dialog box.
After the button is added to the page, you can easily transform it into a control using VBScript. For controls, a good place to put the related script is at the bottom of the page. So, move the insertion point to the bottom of the page and select
Insert | Script from the menu. Set the language property by selecting the radio button labeled Visual Basic Script. Then enter the code from Listing 27.2 into the input area. Finish by closing the Script dialog box and saving the page. You can load your
VBScript-enhanced page into your browser by clicking on the Preview in Browser button. As long as your browser supports VBScript, you can test your new button control!
Listing 27.2. A script with a method call.
Option Explicit Dim Counter Sub funButton_OnClick() Counter = Counter + 1 funButton.Value = Counter End Sub
When you use form elements to execute scripts in your page, youre using intrinsic HTML controls. These controls are intrinsic because theyre built into standard HTML. Controls you can use with VBScript include buttons, text fields, text
areas, radio buttons, and checkboxes.
Buttons are one of the coolest controls to add to your page. You can add them anywhere in your page by selecting Push button on the Forms toolbar and then associating the push button with a script.
With button controls, you can boost the fun level of your pages. Figure 27.7 shows a page with four button controls. By passing a parameter from the button to a subroutine call, the same routine can be used to handle input from multiple buttons. The
steps you can use to add identical button controls to any of your existing pages follow:
Figure 27.7. Adding button controls to your pages.
Sub DisplayDialog(buttonValue) Msgbox "When you clicked on button # " & buttonValue & _ " a parameter was passed to the DisplayDialog subroutine." End Sub
By examining the steps taken to create the button controls, you can learn many things about how buttons are used in Web pages. You added buttons to the page using the Forms toolbar. For finer control over the button, you can assign a procedure to
execute when the button is clicked by using the ONCLICK attribute. You can follow the procedure name with parameters in a comma-separated list. When the buttons you created earlier are clicked, one parameter is passed to a
procedure called DisplayDialog. Depending on which button is pressed, the parameter value is either 1, 2, 3, or 4.
The main body of the script is a subroutine called displayDialog. The routine accepts a parameter so that it can be used to display messages about any of the buttons being clicked. Although parameter passing is right for
some input handling, many times you want each button on the page to drive related and unique events. Following this scenario, the displayDialog subroutine would be rewritten as four event-driven subroutines:
Sub Button1_OnClick Insert code to handle click on Button1 End Sub Sub Button2_OnClick Insert code to handle click on Button2 End Sub Sub Button3_OnClick Insert code to handle click on Button3 End Sub Sub Button4_OnClick Insert code to handle click on Button4 End Sub
Other events, methods, and attributes you can use with buttons are shown in Table 27.3.
Attributes | Events | Methods |
Enabled | OnClick | Click |
Form | OnFocus | Focus |
Name | ||
Value |
With text controls, you can boost interactivity. A text control allows users to input one line of data. You can add a text control anywhere in your page by selecting One-Line Text Box from the Forms toolbar and then associating the text box with a
script.
At the click of a button, your script can display an immediate response to a users text entry (see Figure 27.8). Here is how you can add identical controls to any of your existing pages:
Figure 27.8. Adding text controls to your pages.
Option Explicit Sub displayButton_OnClick Msgbox "You entered: " & funText.Value End Sub
If you examine the steps taken to create the text and push button controls, you can see how text controls are used in Web pages. Because text controls are typically used with buttons, you usually have to add both a one-line text box and a push button
to the page. The script embedded in the page includes a single event-driven subroutine called displayButton_OnClick, which automatically displays a message box when the button is clicked.
To have some real fun with text controls, you need to use events directly related to whats happening with the text control itself, such as OnFocus and OnBlur. These events are driven by
the user selecting different text controls on the page (see Figure 27.9). To direct output to the text controls, you must insert them in a named form, which allows you to target the form by using a method call.
Figure 27.9. Updating text controls on the page.
These are the steps you can take to create updating text controls like those shown in the example:
Option Explicit Sub funTextA_OnFocus() Dim form Set form = document.coolForm form.funTextA.Value = "Control A has focus!" End Sub Sub funTextA_OnBlur() Dim form Set form = document.coolForm form.funTextA.Value = "Control A has lost focus!" End Sub Sub funTextB_OnFocus() Dim form Set form = document.coolForm form.funTextB.Value = "Control B has focus!" End Sub Sub funTextB_OnBlur() Dim form Set form = document.coolForm form.funTextB.Value = "Control B has lost focus!" End Sub Sub funTextC_OnFocus() Dim form Set form = document.coolForm form.funTextC.Value = "Control C has focus!" End Sub Sub funTextC_OnBlur() Dim form Set form = document.coolForm form.funTextC.Value = "Control C has lost focus!" End Sub
Events, methods, and attributes you can use with text controls are shown in Table 27.4.
Attributes | Events | Methods |
DefaultValue | OnBlur | Blur |
Enabled | OnFocus | Focus |
Form | Select | |
Maxlength | ||
Name | ||
Size | ||
Value |
Radio button and checkbox controls are used just as you would use their corresponding form elements. You should use radio button controls when you want users to make only one selection and checkbox controls when you want to allow them to make several
selections.
One use for radio button and checkbox controls in your Web pages is to create interactive surveys like the one shown in Figure 27.10.
Figure 27.10. Radio button and checkbox controls.
You can easily create a similar form. Start by creating the form using these steps:
After you create the form, you need to define controls for the form and add the script. You can do this as follows:
Dim tempAge Dim tempWeb Sub setAge(inputAge) tempAge = inputAge Call displayStatus End Sub Sub setWeb() Dim Result tempWeb = Result If webFun.Checked Then Result = Result & "fun " End If If webBus.Checked Then Result = Result & "business " End If If webRes.Checked Then Result = Result & "research " End If tempWeb = Result Call displayStatus End Sub Sub displayStatus() theResult.Value = "You are " & tempAge & Â" and use the Web for: " & tempWeb End Sub
If you examine the steps used to create the controls, you can see that adding radio button and checkbox controls to your page is more complex than adding other controls used previously. However, once you understand the basics of these controls, you can
use them like a real pro.
When you add radio button controls, use a single name for all radio buttons in a particular group. In the example, the group userAge is used. Next, set up an event with a specific value, using OnClick. In the example, the setAge subroutine is passed these parameter values: under 18, 18-21, 21-25, 26-35, or over 35.
When you add checkbox controls, each checkbox is given a unique name. Next, you set up an event to call. In the example, the setWeb subroutine is called when a checkbox is selected. Within the subroutine, a series of If...Then statements assign values to a result variable based on the checkboxs name.
The events, methods, and attributes you can use with radio button and checkbox controls are shown in Table 27.5.
Attributes | Events | Methods |
Checked | OnClick | Click |
Enabled | OnFocus | Focus |
Form | ||
Maxlength | ||
Name | ||
Size | ||
Value |
Text window controls are almost identical to text controls. The key differences are that with a text window control, users can enter more than one line of text.
You can use text window controls to let users input large amounts of data. When you create a text window control, you define the size of the window in rows and columns. The number of rows defines the height of the window in lines, and the number of
columns defines the width of the window in characters.
As shown in Figure 27.11, you can use a text window control to gather information from a user, then respond instantly. When you gather information from the reader, you will often use a text window control and a push button control. You can create
similar controls as follows:
Figure 27.11. Creating text window controls.
Dim tempAge Dim tempWeb Sub coolWindow_OnFocus() Alert "We welcome your comments." End Sub Sub cmdButton_OnClick() Msgbox "Thankyou!" End Sub
Events, methods, and attributes you can use with text controls are shown in Table 27.6.
Attributes | Events | Methods |
DefaultValue | OnBlur | Blur |
Enabled | OnFocus | Focus |
Form | Select | |
Name | ||
Rows | ||
Columns |
Password controls allow users to enter password information. All text entered in a password control is displayed as asterisks. You add a password control to your page by setting the Password field of a one-line text box to Yes. Because a password
control is really a disguised
one-line text control, the options for a password control are identical to a one-line text controls options.
Figure 27.12 shows how you can use password controls in your Web pages. Here are the steps you can use to create the same controls:
Figure 27.12. Adding password controls to the page.
Sub inputButton_OnClick() Dim Password Password = userPassword.Value If Len(Password) < 8 Then Alert "Your password must be at least Âeight characters in length." userPassword.Value = "" End If End Sub
Events, methods, and attributes you can use with text controls are shown in Table 27.7.
Attributes | Events | Methods |
DefaultValue | OnBlur | Blur |
Enabled | OnFocus | Focus |
Form | Select | |
Maxlength | ||
Name | ||
Size | ||
Value |
VBScript is a powerful tool for adding interactivity to your pages. Still, there are times when you want to submit data to a server. Ideally, you would use VBScript to verify the data before submitting it, which eliminates the back-and-forth traffic
between the client and server.
Submitting the contents of a VBScript-enhanced form to a server isnt much different from submitting a regular form. Just as with regular forms, the FORM element has an Action and a Method. To this, you add three attributes: Name, Language, and OnSubmit.
The Name attribute gives the form a name, so you can refer to it with a method in your script. The optional Language attribute identifies the scripting language and the OnSubmit attribute specifies a subroutine to execute when the form is submitted. This subroutine is generally not the one that submits the forms contents to the server; rather, its the subroutine executed after the
contents are submitted to the server.
After you create your controls on the page, you need to define a handler for the form and then specify attributes for the form. The steps to do this are as follows:
To submit the form to a server, add a push button control as the last element of the form. Although you want to submit the form to a server, you still want to use the Normal push button type. After you add the push button to the page, open its
properties. Then perform these steps:
Within a subroutine executed when the button is clicked, add a method reference to submit the forms contents, as shown in this example:
Sub custFeedback_OnClick document.myForm.Submit End Sub
In this example:
custFeedback is a subroutine named after the button on the page.
OnClick is the event you want to check for.
document references the current page.
myForm is the name of the form.
Submit is the action to be carried out when the button is clicked.
Figure 27.13 shows a VBScript-enhanced form that submits data to a server.
Figure 27.13. VBScript-enhanced feedback form.
A complete listing of the steps used to create the form follows. You can use these steps to help you create your own forms that use VBScript and submit data to a server:
dim addCrLf : addCrLf = Chr(13) & Chr(10) & Chr(13) & Chr(10) Sub custFeedback_OnClick If Len(document.frmFeedback.customerEmail.value) = 0 then Alert "At a minimum, you must enter your e-mail address." & _ "This allows us to respond to your comments." Else Msgbox "Your feedback will be submitted with an action of " & _ document.frmFeedback.Action & addCrLf & _ "Click the OK button to confirm." document.frmFeedback.Submit End If End Sub Sub SubmitFeedback MsgBox "Form was submitted." MsgBox "The ACTION used is " & Âdocument.frmFeedback.Action & addCrLf & _ "The METHOD used is " & document.frmFeedback.Method & addCrLf & _ "The ENCODING used is " & document.frmFeedback.Encoding & addCrLf & _ "The TARGET for results from server is " & document.frmFeedback.Target End Sub
NOTE
The source code contains the VBScript code continuation character. When you see the underscore at the end of a line, it means the line actually continues to the next line, but the programmer decided to break it up so its easier to read.
If you try to submit the form without filling in the required data, youll see an alert box (see Figure 27.14). Although the current script looks only for the e-mail address, you can easily make other data entries mandatory, too.
Figure 27.14. If you dont fill out the required fields, an alert box is displayed.
When you click the Submit Feedback button, you see the message box shown in Figure 27.15. Although this message box isnt essential to the scripts working, its an example of how you could let users verify that they want to submit the
form.
Figure 27.15. If you click the Submit Feedback button, a confirmation dialog box is shown.
VBScript is a powerful tool for enhancing your Web pages. Because its 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.
After you understand procedures, youre ready to add interactivity to your pages. Using HTML controls, you can create interactive buttons, text areas, checkboxes, and much more. Because VBScript takes advantage of existing HTML controls, you can
easily perform complex tasks, such as validating form input. You can even submit your input to a server for processing after validation.