by David Blankenbeckler
In Chapter 27, "Manipulating Web Components Using JavaScript," you learned how to use JavaScript in your Web pages. There is another choice for writing scripts for your HTML documents: VBScript. The VBScript language works in much the same manner as JavaScript: The code is written and saved in text format in your HTML documents. When the browser sees VBScript code, it automatically interprets and runs it.
Many programmers are familiar with Microsoft's Visual Basic programming language. This is one of the key benefits that VBScript has over JavaScript; VBScript is a subset of the Visual Basic programming language. It is fully upward compatible with Visual Basic.
VBScript is currently only supported by Microsoft Internet Explorer. This is a major drawback because Netscape has such a large user base and does not currently support VBScript.
This chapter presents the VBScript programming language so that you can successfully implement VBScript into your HTML files. This chapter should also serve as a convenient reference to the VBScript language.
As mentioned, VBScript is a subset of Visual Basic. Readers who are very familiar with Visual Basic may simply need to know what Visual Basic features are not available in VBScript. This section briefly discusses the major differences between the two. Readers who are unfamiliar with Visual Basic should skip ahead to the next section, "Using Scripts in HTML Files."
The following list identifies the most significant features of Visual Basic that are not supported by VBScript:
As you may notice, most of the exclusions from VBScript were made because they didn't make sense in an HTML scripting language or they violated the security features necessary for Web use. For example, the file I/O capabilities of Visual Basic would clearly cause security violations with Web applications.
Scripts are embedded in HTML files using the <SCRIPT>...</SCRIPT> pair of tags. The <SCRIPT> tags can appear either in the <HEAD> or <BODY> section of the HTML file. The advantage of placing them in the <HEAD> section is that they will be loaded and ready before the rest of the document loads.
The only attribute currently defined for the <SCRIPT> tag is LANGUAGE=. This attribute is used to specify the scripting language. There are currently two values defined: "JavaScript" and "VBScript". The following syntax should be used for your VBScript applications:
<SCRIPT LANGUAGE="VBScript"> ' INSERT ALL VBScript HERE </SCRIPT>
| NOTE |
You might have noticed that the comment is not enclosed in normal <-- and --> tags for HTML comments. This is because VBScript supports the same comment style as Visual Basic. A single apostrophe or the Rem statement is used to indicate a comment in VBScript (and Visual Basic) |
The difference in commenting syntax between HTML and VBScript allows you to hide the VBScript code inside an HTML comment so that older browsers that don't support it won't read it, as in the following example:
<SCRIPT LANGUAGE="VBScript"> <!-- From here the VBScript code is hidden ' INSERT ALL VBScript HERE ' this is where the hiding ends --> </SCRIPT>
The examples in this chapter do not include the script hiding feature simply to make the code a little more readable. However, you should always include this in your code so that non-VBScript-enabled browsers can be handled properly.
Let's start with a simple example to show you the VBScript language and give you an idea of some of the things that are possible. The following program prompts the user for his or her name and then displays a short message using the name that was entered:
<HTML><HEAD>
<TITLE>A VBScript Example</TITLE>
<SCRIPT LANGUAGE="VBScript">
dim name
name = InputBox("Hello! What is your name?")
Document.Write "Hello " & name & "! I hope you like VBScript!"
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Figure 28.1 shows the input prompt. Figure 28.2 shows the output to the screen after the name was entered.
Figure 28.1 : A VBScript example, before you've entered your name.
Figure 28.2 : A VBScript example, after you've entered your name.
This example displays a prompt with the InputBox function. The value obtained is stored in a variable called name. The variable is tfe sol:Aned with other text and displayed in the browser's window using the Document.Write method.
Now that you have briefly glimpsed the functionality available with VBScript, the chapter continues with a tutorial of the language itself.
A VBScript variable must start with a letter. A number cannot be used as the first character of a variable name but can be used after the first character. VBScript is not case sensitive.
A variable is declared in VBScript with the Dim statement, as in the following:
Dim myvariable
Multiple variables can be declared together if you separate each variable name by a comma, as in the following:
Dim myvariable, x, y, AVeryLongVariableNameWithANumberInIt8
| NOTE |
Like Visual Basic, VBScript supports the use of variables without first declaring them with Dim. However, this is generally not considered good programming practice. The Option Explicit statement will force all variables to require declaration with the Dim statement. This statement should be placed at the beginning of VBScript code to ensure that the variable names you have chosen are spelled consistently throughout your program; an error message will appear the first time you try to run the script if there are any undeclared variables being used |
There are two scopes available for variables: global and local. A global variable can be accessed anywhere in the script and lasts as long as the script is running. A local variable is declared inside a procedure or function and can be accessed only in that procedure or function. In addition, local variables only last as long as you are executing that procedure.
The following section discusses the types of data that can be assigned to variables in VBScript.
Like JavaScript, VBScript is a loosely typed language, meaning that you do not have to specify a data type when a variable is declared. All variables are of type Variant. The Variant is automatically converted to the following subtypes as necessary:
Boolean-True or false
Byte-Integer from 0 to 255
Date-Represents a date or time from January 1, 100, to December 31, 9999.
Double-A floating point number from +/- 4.94065645841247E-324 to +/- 1.79769313486232E308
Empty-Indicates that a value has not been assigned yet
Error-Indicates an error number
Integer-An integer from -32,768 to 32,767
Long-An integer from -2,147,483,648 to 2,147,483,647
Null-Purposefully set to no valid data
Object-An object
Single-A floating-point number from +/- 1.401298EÐ45 to +/- 3.402823E38.
String-A string
As mentioned, VBScript automatically converts a Variant to the appropriate subtype as needed. Consider the following example:
<HTML><HEAD> <TITLE>A Data Type Example</TITLE> <SCRIPT LANGUAGE="VBScript"> dim fruit dim numfruit dim temp fruit = "apples" numfruit = 12 numfruit = numfruit + 20 temp = "There are " & numfruit & " " & fruit & "." Document.Write temp </SCRIPT> </HEAD> <BODY> </BODY> </HTML>
VBScript-enabled browsers will correctly handle this example with the following output:
There are 32 apples.
The VBScript interpreter will treat the numfruit variable as an integer when 20 is added and then as a string when it is combined into the temp variable.
Literals are values in a program that don't change. In VBScript there isn't a CONST statement, as in Visual Basic, that can be used to represent some constant value; rather you simply use a variable.
The way that values are represented in VBScript can be broken into five categories: integers, floating points, booleans, dates, and strings. Each of these is discussed in the following sections.
Integers in VBScript are represented in base 10. Integers are expressed as numbers without a decimal point, e, or E. The following are examples of integer literals:
10
4920056843
A floating-point literal is comprised of the following parts:
In order to be classified as a floating-point literal, as opposed to an integer, there must be at least one digit followed by either a decimal point, e, or E. Examples of floating-point literals are
9.87
-0.85e4
0.98E-3
The boolean literal is used to indicate a true or false condition. There are simply two values:
True
False
A date or time can be expressed in VBScript by enclosing it within the # character. The following are examples of date literals:
#2-12-69#
#9-4-1996#
#2/12/69#
#10:35:00#
#20:45:30#
#8:45:30p#
#2/12/69 8:45:30p#
#8:45:30p 2/12/69#
A string literal is represented by zero or more characters enclosed in double quotes. The following are examples of string literals:
"the cat ran up the tree"
"100"
Unlike JavaScript, the VBScript language has direct support for arrays. This section assumes that you already have a basic understanding of arrays.
Declaring arrays is very similar to declaring other types of variables. To do so, you use the Dim statement and follow the array name by the upper bound in parentheses. For example, the following line would create an array of 12 elements, called monthlySales:
Dim monthlySales(11)
Notice that 11 is used but there are 12 elements. This is because the first element of an array in VBScript is always 0. (The feature of Visual Basic that allows you to declare arrays with a lower bound other than 0 is not supported in VBScript.)
To access an array element, use the variable name followed by the element in parentheses. For example, to reference the fifth element, you would use the following:
monthlySales(4)
Multidimensional arrays (up to 60 dimensions) are supported in VBScript. To declare a multidimensional array, add an upper bound parameter for each dimension, separated by commas. For example, consider the following 3D array declaration:
ThreeDCoord(99,99,99)
VBScript also supports dynamic arrays with the ReDim statement. For an array to be declared dynamic, it must initially be declared without upper bounds (that is, empty parentheses). The ReDim statement can then be used to set the upper bounds later in the script. The ReDim statement can be used as often as necessary. Unless the Preserve keyword is used, the contents of the array will be lost after each ReDim. Also, if an array is redimensioned to a smaller size with the Preserve keyword, the excess contents will be lost. Consider the following example:
Dim monthlySales() ' VBScript code can go here ' Later a ReDim statement is used ReDim monthlySales(11) monthlySales(7) = 20000 ReDim Preserve montlySales(23) ' The monthlySales(7) value is preserved ' and the array is enlarged to 24 elements ReDim monthlySales(35) ' All monthlySales contents are lost since Preserve was not used
A set of literals, variables, and/or operators that evaluates to a single value is an expression. The single value can be a string, number, or boolean value. There are four types of expressions in VBScript:
An expression that evaluates to a number is an arithmetic expression, as in the following:
( 3 + 4 ) * (84.5 / 3)
This expression would evaluate to 197.1666666667.
An expression can also evaluate to a string. Literal strings are enclosed in double quotes, as in the following:
"The dog barked" & barktone & "!"
This expression might evaluate to "The dog barked ferociously!".
A date can be used in an expression as well. To assign a literal date to a variable, enclose the date in # characters. The date can then be used in an expression. For example, the following code will assign a date to a variable and then use the variable in an expression to add 5 days:
Dim thisDay thisDay = #8/17/96# Document.Write "In 5 days it will be " & (thisDay + 5)
The output from this code follows:
In 5 days it will be 8/22/96
This capability, combined with the many date functions in VBScript, makes working with dates easy. The VBScript date functions are covered in the "Date and Time Functions" section.
VBScript also supports logical expressions. These expressions evaluate to either true or false. They are then typically used with conditional statements. An example of a logical expression follows:
temp > 32
This expression can evaluate to true or false, depending on the value of temp.
Operators are used to perform some operation on data. Operators can return either a numeric value, a string value, or a boolean value to indicate true or false. The VBScript operators are grouped into the following categories: assignment, comparison, arithmetic, string, logical, and bitwise logical.
The assignment operator is the equal sign, which assigns the value of the right operand to the left operand. For example, the following line assigns the value of 3 to the variable x:
x = 3
The purpose of a comparison operator is to compare two operands and return true or false on the basis of the comparison. The following comparison operators are supported by VBScript:
= returns true if the operands are equal.
<> returns true if the operands are not equal.
> returns true if the left operand is greater than the right operand.
>= returns true if the left operand is greater than or equal to the right operand.
< returns true if the left operand is less than the right operand.
<= returns true if the left operand is less than or equal to the right operand.
Is returns true if the left object is the same as the right object.
In addition to the standard operators (+, -, *, /) for addition, subtraction, multiplication, and division, VBScript supports the following arithmetic operators:
num1\num2-The integer division operator will divide num1 by num2 and return an integer result.
var1 Mod var2-The modulus operator returns the remainder of the integer division of var1 by var2.
-num-The unary negation operator simply negates num.
num^exp-The exponentiation operator will raise num to the power of exp.
VBScript has a special operator, &, that is used for concatenating strings: str1 & str2 combines str1 with str2.
VBScript supports the following logical operators, which return a boolean value:
If two numeric expressions are used with the logical operators defined in the previous section, then a bitwise comparison will be performed. The following operators are supported:
Statements form the underlying structure of a program and are used to specify the path of execution. Statements are used for branching based on conditions and looping through a section of code until a specified condition is met. VBScript statements are divided into two categories: conditional and looping.
Conditional statements provide the ability to perform steps based on the outcome of a comparison. VBScript provides this support through the If...Else and Select Case statements.
The If...Then...Else statement allows you to check for a certain condition and execute statements based on that condition. The optional Else statement allows you to specify a set of statements to execute if the condition is not true.
If condition Then ' statements for true condition Else ' statements for false condition End If
The End If statement is only necessary if there is more than one line of statement following the true or false condition.
If x = 10 Then Document.Write "x is equal to 10, setting x = 0." x = 0 Else Document.Write "x is not equal to 10." End If
Note that the End If statement is not necessary in this simple comparison:
If myVar = True Then yourVar = false
The Select Case statement is useful when a single condition needs to be checked and there are multiple outcomes based on the result.
Select Case expr
Case n
' statements for this case
Case m
' statements for this case
'... additional case statements as necessary
[Case Else]
' statements for the default case
End Select
The following example would evaluate the variable Day and print to the screen the appropriate message:
Select Case Day
Case 0
Document.Write "Today is Sunday.<BR>"
Case 1
Document.Write "Today is Monday.<BR>"
Case 2
Document.Write "Today is Tuesday.<BR>"
Case 3
Document.Write "Today is Wednesday.<BR>"
Case 4
Document.Write "Today is Thursday.<BR>"
Case 5
Document.Write "Today is Friday.<BR>"
Case 6
Document.Write "Today is Saturday.<BR>"
Case Else
Document.Write "ERROR: Invalid value for Day!<BR>"
End Select
Loop statements provide a means for looping through a section of code until an expression evaluates to true. VBScript provides three types of loop statements:
The For loop will set var to init, then loop through a section of VBScript statements incrementing var by 1 before each loop. When var = final, the loop executes one final time, the loop ends, and the statement following Next is executed. If var is incremented to a value greater than final, the loop will also terminate.
If Step is specified, var will be incremented (or decremented) by the value of step each loop. When step is negative, the value of var will be decremented by step each loop. In this case, when var is less than final, the loop will terminate.
An optional Exit For statement can be used to terminate the loop at any time by placing one or more Exit For statements inside the loop.
For var = init To final [Step step] ' statements to execute while looping Next
For x=0 To 10 Step 2 y = x * 25 Document.Write "x=" & x & " y=" & y & "<BR>" Next
This example will loop through the code until x is equal to 10. Figure 28.3 shows the output.
Figure 28.3 : A For...Next loop example.
The While loop will continue as long as a specified condition evaluates to true. When condition no longer evaluates to true, the loop will immediately exit and the statement following Wend will be executed.
While condition ' statements to execute while looping Wend
x = 0 While x <= 10 y = x * 25 Document.Write "x="+ x + " y=" + y + "<BR>" x = x + 2 Wend
This will produce the same result as the For loop example in Figure 28.3.
The Do loop provides several forms, depending on how the loop is exited. You can exit the loop with either a While or an Until condition. In addition, an optional Exit Do can be used either as the sole means of exiting the loop or in combination with While or Until.
A Do While loop will continue to execute as long as a certain condition remains true.
A Do Until loop will continue to execute until a certain condition is true.
Do While condition ' statements to execute while looping [Exit Do] ' statements to execute while looping Loop Do Until condition ' statements to execute while looping [Exit Do] ' statements to execute while looping Loop
The Until or While keyword can also be placed at the end of the loop. It is simply a matter of taste; the same result will be obtained:
Do ' statements to execute while looping Loop [Until|While]
Do y = x * 25 Document.Write "x="+ x + " y=" + y + "<BR>" x = x + 2 Loop Until x > 10 Do While x <= 10 y = x * 25 Document.Write "x="+ x + " y=" + y + "<BR>" x = x + 2 Loop
These two examples will produce the same result as the For...Next loop and the While...Wend loop examples in Figure 28.3.
A procedure is a set of statements that can be called as needed from your main code or other procedures. VBScript supports the use of two types of procedures: Sub, which does not have a return value, and Function, which does.
Both types of procedure can have one or more parameters passed to it. Because VBScript is a loosely typed language, it is not necessary to define parameter or return types for a VBScript procedure.
Because procedures must be defined before they are called, they should always be placed at the beginning of an HTML document in the <HEAD> section.
The Sub procedure should be used when a procedure does not have a return value.
Sub SubName([param1][,param2]...[,paramN]) ' sub procedure statements End Sub
To call this procedure, use the following syntax:
SubName [param1][,param2]...[,paramN]
The following example shows the use of the Sub procedure by creating a procedure to calculate and display the area of a circle:
<HTML><HEAD> <TITLE>A Sub Procedure Example</TITLE> <SCRIPT LANGUAGE="VBScript"> Sub PrintAreaOfCircle(radius) Document.Write "A circle of radius " & radius & " cm has an area of " Document.Write 3.14159 * radius^2 Document.Write " cm<SUP>2</SUP>.<BR>" End Sub ' Now we will call the Sub PrintAreaOfCircle(4) PrintAreaOfCircle(6) PrintAreaOfCircle(10.5) </SCRIPT> </HEAD> <BODY> </BODY> </HTML>
Figure 28.4 shows the output from this example.
Figure 28.4 : An example of a Sub procedure.
The Function procedure should be used when there is value returned at the exit of the procedure.
Function fnName([param1][,param2]...[,paramN]) ' function statements; fnName = expr End Function
Notice that the return value for a function is given by setting the function name, fnName, equal to some value before the end of the function.
The syntax for calling a function follows:
returnVar = fnName([param1][,param2]...[,paramN])
The following example shows the use of the Function procedure by creating a procedure to calculate and display the area of a circle. The output from this example is the same as the output from the Sub example in Figure 28.4:
<HTML><HEAD> <TITLE>A Function Procedure Example</TITLE> <SCRIPT LANGUAGE="VBScript"> Function AreaOfCircle(radius) AreaOfCircle = 3.14159 * radius^2 End Function ' Now we will call the Function three times like before Document.Write "A circle of radius 4 cm has an area of " & AreaOfCircle(4) Document.Write " cm<SUP>2</SUP>.<BR>" Document.Write "A circle of radius 6 cm has an area of " & AreaOfCircle(6) Document.Write " cm<SUP>2</SUP>.<BR>" Document.Write "A circle of radius 10.5 cm has an area of " Document.Write AreaOfCircle(10.5) & " cm<SUP>2</SUP>.<BR>" </SCRIPT> </HEAD> <BODY> </BODY> </HTML>
VBScript contains a wide selection of built-in functions. It is useful to categorize them as follows:
The following sections discuss the functions for each of these categories.
VBScript provides a wide range of mathematical functions. In the following function declarations, numExpr can be either a number or an expression that evaluates to a number:
Abs(numExpr)-Returns the absolute value of numExpr.
Atn(numExpr)-Returns the arctangent of numExpr.
Cos(numExpr)-Returns the cosine of numExpr.
Exp(numExpr)-Returns e numExpr, where e is Euler's constant.
Fix(numExpr)-Returns the integer portion of numExpr. If the number is negative, the next greater integer will be returned.
Int(numExpr)-Returns the integer portion of numExpr. If the number is negative, the next lower integer will be returned.
Log(numExpr)-Returns the natural log of numExpr.
Rnd([numExpr])-Returns a pseudorandom number. The number is not really random because the same seed will always produce the same result. If numExpr is used, the result will be as follows: If numExpr = 0, then Rnd returns the last random number generated.
If numExpr > 0, then Rnd returns the next random number in the sequence.
If numExpr < 0, then Rnd returns a random number based on the seed, numExpr. The same seed will always return the same number.
The Randomize statement will generate a seed for the Rnd function based on the system clock. This will provide for a much better illusion of randomness, as in the following example:
Randomize
x = Rnd()
Sgn(numExpr)-Returns 1 if numExpr is greater than 0, Ð1 if numExpr is less than 0, and 0 if numExpr is equal to 0.
Sin(numExpr)-Returns the sine of numExpr.
Sqr(numExpr)-Returns the square root of numExpr.
Tan(numExpr)-Returns the tangent of numExpr.
Date-Returns the current date from the system clock.
DateSerial(year, month, day)-Returns a value of subtype Date to represent the year, month, and day that were passed.
Day(date)-Returns an integer between 1 and 31 to represent the day for the date that was passed.
Hour(time)-Returns an integer between 0 and 23 to represent the hour for the time that was passed.
Minute(time)-Returns an integer between 0 and 59 to represent the minute for the time that was passed.
Month(date)-Returns an integer between 1 and 12 to represent the month for the date that was passed.
Now-Returns the current date and time based on the system clock.
Second(time)-Returns an integer between 0 and 59 to represent the second for the time that was passed.
Time-Returns the current time from the system clock.
TimeSerial(hour, minute, second)-Returns a value of subtype Date to represent the hour, minute, and second that were passed.
Weekday(date [, firstday])-Returns an integer between 1 and 7 that represents the current day of the week for date. By default, Sunday is represented by 1, Monday 2, and so on. If a firstday parameter is passed, then another day can be set to be represented by 1. For example, if 2 is passed as the firstday parameter, then Monday would be represented by 1.
Year(date)-Returns an integer that represents the year in date; for example, 1996.
VBScript has a wide array of built-in functions to assist you in dealing with strings. In the following function declarations, strExpr can be either a string or an expression that evaluates to a string:
Asc(strExpr)-Returns an integer representing the ANSI code for the first character of strExpr.
Chr(ANSICode)-Returns the character represented by ANSICode.
Hex(number)-Returns a string that represents number in hexadecimal.
InStr([startPos,] string, srchstr [, compType])-Returns the position of the first occurrence of srchstr in string. If startPos is specified, then the search will begin at that position. The compType parameter can be either 0 or 1. The default value of 0 is case sensitive. A compType of 1 indicates that the search should not be case sensitive.
LCase(strExpr)-Converts strExpr to lowercase and returns it as a string.
Left(strExpr, numChars)-Returns a substring of strExpr that begins at the first position (on the left) and is numChars in length.
Len(strExpr | varName)-If a string expression is passed, Len returns the length of that string. If a variable name is passed, Len returns the number of bytes required to store that variable.
LTrim(strExpr)-Removes all leading spaces from strExpr and returns it as a string.
Mid(strExpr, startPos, numChars)-Returns a substring of strExpr that begins at startPos and is numChars in length.
Oct(number)-Returns a string that represents number in octal.
Right(strExpr, numChars)-Returns a substring of strExpr that begins at the last position (on the right) and is numChars in length.
RTrim(strExpr)-Removes all trailing spaces from strExpr and returns it as a string.
StrComp(strExpr1, strExpr2 [,compType])-Compares strExpr1 and strExpr2. If they are equal, 0 is returned. Ð1 is returned if strExpr1 is less than strExpr2. 1 is returned if strExpr1 is greater than strExpr2. If either string is null, Null is returned.
The compType parameter can be either 0 or 1. The default value of 0 is case sensitive. A compType of 1 indicates that the search should not be case sensitive.
String(length, character)-Returns a string of repeating character that is length in length.
Trim(strExpr)-Removes all leading and trailing spaces from strExpr and returns it as a string.
UCase(strExpr)-Converts strExpr to uppercase and returns it as a string.
InputBox(prompt [, title][, default][, xPos][, yPos][, helpFile, context])-This function will display a dialog box with a text field. The contents of the text field will be returned. The parameters are defined as follows:
prompt-The prompt displayed in the dialog box.
title-The text displayed on the title bar of the dialog box.
default-The default contents of the text field.
xPos-The distance (in twips) of the dialog box from the left edge of the screen.
yPos-The distance (in twips) of the dialog box from the top of the screen.
helpFile-The filename of the help file that should be used for context-sensitive help.
context-The context number for the appropriate help topic in helpFile.
The following code is an example of how to use InputBox. Figure 28.5 shows the screen output:
<HTML><HEAD>
<TITLE>A InputBox Example</TITLE>
<SCRIPT LANGUAGE="VBScript">
dim Name
Name = InputBox("Please enter your name.", "This is an InputBox!", "John Doe")
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Figure 28.5 : An example of an input box.
MsgBox(prompt[, buttons][, title][, helpfile, context])-The MsgBox function will display a dialog box with one or more buttons, as configured by the buttons parameter. The parameters are defined as follows:
prompt-The prompt displayed in the dialog box.
buttons-A number that specifies the number and type of buttons to display in the dialog box. The number is arrived at by adding together four numbers to specify the number and type of buttons, the icon style, the default button, and the modality of the dialog box. The buttons configurations are as follows:
| Effect | |
|
| OK button |
|
| OK and Cancel buttons |
|
| Abort, Retry, and Ignore buttons |
|
| Yes, No, and Cancel buttons |
|
| Yes and No buttons |
|
| Retry and Cancel buttons |
| Effect | |
| No icon | |
| Critical Message icon | |
| Warning Query icon | |
| Warning Message icon | |
| Information Message icon |
| Effect | |
| First button | |
| Second button | |
| Third button | |
| Fourth button |
| Effect | |
| Application Modal |
| System Modal |
title-The text displayed on the title bar of the dialog box.
helpFile-The filename of the help file that should be used for context-sensitive help.
context-The context number for the appropriate help topic in helpFile.
The return value provides the button that was selected:
| Button Selected | |
| OK | |
| Cancel | |
| Abort | |
| Retry | |
| Ignore | |
| Yes | |
| No |
The following code is an example of how to use the MsgBox function:
<HTML><HEAD>
<TITLE>A MsgBox Example</TITLE>
<SCRIPT LANGUAGE="VBScript">
dim answer
answer = MsgBox("You are about to become a VBScript expert!" & Chr(13) &
"Are you ready?", 36 , "This is a MsgBox!")
if answer = 6 then Document.Write "That is great! <BR>"
if answer = 7 then Document.Write "Oh, that's too bad. <BR>"
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
This script will display a dialog box with Yes and No buttons (4) and a Warning Query icon (32). This is specified by the value 36 (32+4). The Chr(13) will create a carriage return after the first sentence of the prompt. The script will then respond depending on whether Yes or No was returned. Figure 28.6 shows the screen output.
Figure 28.6 : An example of a message box.
VBScript provides many functions to help in dealing with data types. The functions in the following list prefixed with C are used to convert a value to a Variant of a specific subtype. Those prefixed with Is can be used to determine if an expression can be converted to a specific subtype:
CBool(expr)-Returns expr converted to subtype Boolean. If expr is 0, then false will be returned. True will be returned if expr is unequal to 0. A type mismatch runtime error will occur if expr does not represent a numeric value.
CByte(expr)-Returns expr converted to subtype Byte. If expr cannot be converted to subtype Byte, a type mismatch runtime error will occur.
CDate(expr)-Returns expr converted to subtype Date. If expr cannot be converted to subtype Date, a type mismatch runtime error will occur.
CDbl(expr)-Returns expr converted to subtype Double. If expr cannot be converted to subtype Double, a type mismatch or overflow runtime error will occur.
CInt(expr)-Returns expr converted to subtype Integer. If expr cannot be converted to subtype Integer, a type mismatch or overflow runtime error will occur.
CLng(expr)-Returns expr converted to subtype Long. If expr cannot be converted to subtype Long, a type mismatch or overflow runtime error will occur.
CSng(expr)-Returns expr converted to subtype Single. If expr cannot be converted to subtype Single, a type mismatch or overflow runtime error will occur.
CStr(expr)-Returns expr converted to subtype String.
If expr is Boolean, then either true or false is returned.
If expr is a Date, then a string will be returned in the short date format for the particular system.
If expr is subtype Error, then a string containing the word Error and the error number will be returned.
If expr is Null, a runtime error occurs.
DateValue(string)-Returns a variant of subtype Date to represent the date in string.
IsArray(expr)-Returns a boolean indicating whether expr is an array.
IsDate(expr)-Returns a boolean indicating whether expr can be converted to a date.
IsEmpty(expr)-Returns a boolean indicating whether expr is empty. The intent of this function is to pass a variable name as expr to determine if it has been initialized.
IsNull(expr)-Returns a boolean indicating whether expr contains Null.
IsNumeric(expr)-Returns a boolean indicating whether expr can be evaluated to a numeric value.
IsObject(expr)-Returns a boolean indicating whether expr references a valid object.
LBound(arrayName[, dimension])-Returns the lower bound of arrayName for the dimension indicated. VBScript does not support lower bounds other than zero, so this function is not very useful.
TimeValue(string)-Returns a variant of subtype Date to represent the time in string.
UBound(arrayName[, dimension])-Returns the upper bound of arrayName for the dimension indicated.
Val(strExpr)-Returns the first numeric value found in strExpr. The numeric value must be at the beginning of strExpr. Spaces, tabs, and line feeds will be removed and periods converted to decimal points. The prefixes &O and &H in strExpr can be used to specify octal or hexadecimal values.
VarType(varName)-Returns a number that indicates the Variant subtype of varName according to the following table:
| Subtype | |
| Empty | |
| Null | |
| Integer | |
| Long | |
| Single | |
| Double | |
| Date | |
| String | |
| Automation object | |
| Error | |
| Boolean | |
| Variant | |
| Non-automation object | |
| Byte | |
| Array |
VBScript is an event-driven language, which means it can respond to certain events, such as a mouse click or the loading of a document. An event can cause a section of code (known as an event handler) to execute to allow the program to respond appropriately.
The program that responds to an event is called an event handler. The event handler is specified as an attribute of an HTML tag:
<tagName eventHandler="VBScript Statement or Procedure">
The following example calls the CheckAge Sub when the text field is changed:
<INPUT TYPE=TEXT NAME="AGE" onChange="CheckAge">
The event handler code does not have to be a procedure; it can be a single VBScript statement. Because only a single statement can be used and a separate procedure is more readable, the event handler is typically a separate procedure.
The following list describes the event handlers available in VBScript:
The following example shows a simple event handler script that will validate a value entered into a text field. The user's age is entered in the field, and the event handler will check whether a valid age was entered. If not, a message will appear asking the user to reenter the value. The event handler is called when the AGE field is changed and the focus is moved to another field. Figure 28.7 shows the screen output:
<HTML>
<HEAD>
<TITLE>An Event Handler Example</TITLE>
<SCRIPT LANGUAGE="VBScript">
Sub CheckAge(form)
If ((form.age.value < 0) Or (form.age.value > 120)) Then
alert "Please enter your real age!"
form.age.value = 0
End If
End Sub
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="SURVEY">
Please enter your name and age:<BR>
First<INPUT TYPE=TEXT NAME="FNAME" MAXLENGTH=15 SIZE=10>
MI<INPUT TYPE=TEXT NAME="MI" MAXLENGTH=1 SIZE=1>
Last<INPUT TYPE=TEXT NAME="LNAME" MAXLENGTH=20 SIZE=15><BR><BR>
Age<INPUT TYPE=TEXT NAME="AGE" MAXLENGTH=3 SIZE=2 onChange="CheckAge(SURVEY)">
<P>
Please select your favorite season of the year:<BR>
Spring<INPUT TYPE=RADIO NAME="SEASON" VALUE="Spring">
Summer<INPUT TYPE=RADIO NAME="SEASON" VALUE="Summer">
Fall <INPUT TYPE=RADIO NAME="SEASON" VALUE="Fall">
Winter<INPUT TYPE=RADIO NAME="SEASON" VALUE="Winter">
<P>
Please check all of the outdoor activities that you enjoy:<BR>
Hiking<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Hiking">
Skiing<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Skiing">
Water Sports<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Water">
Cycling<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Cycling">
<P>
<INPUT TYPE=SUBMIT><INPUT TYPE=RESET>
</FORM>
</BODY>
</HTML>
Figure 28.7 : A VBScript event handler example.
The object hierarchy for Microsoft Internet Explorer and VBScript is very similar to and compatible with the JavaScript object hierarchy. The primary difference is that there is no built-in Math, Date, or String object. Of course, these are not needed because there are built-in functions to handle these types of operations.
The reader should refer to Chapter 27 for descriptions of each object and its associated properties, methods, and event handlers. As mentioned, each of these objects applies equally to VBScript except for the Math, String, and Date objects.
The following words are defined as part of the VBScript language
and cannot be used as variable names:
| Abs | Erase | Len | Set |
| And | Err | Log | Sgn |
| Asc | Error | Loop | Sin |
| Atn | Exit | Ltrim | Sqr |
| Call | Exp | Mid | Step |
| Case | Fix | Minut | Str |
| Cbool | For | Mod | StrComp |
| Cbyte | Function | Month | String |
| Cdate | Hex | MsgBox | Sub |
| CDbl | Hour | Next | Tan |
| Chr | If | Not | Then |
| Cint | Imp | Now | Time |
| Clear | InputBox | Oct | TimeSerial |
| CLng | InStr | On | TimeValue |
| Cos | Int | Or | Trim |
| CSng | Is | Preserve | UBound |
| CStr | IsArray | Raise | UCase |
| Date | IsDate | Randomize | Until |
| DateSerial | IsEmpty | ReDim | Val |
| DateValue | IsNull | Rem | VarType |
| Day | IsNumeric | Right | Weekday |
| Dim | IsObject | Rnd | Wend |
| Do | Lbound | RTrim | While |
| Else | Lcase | Second | Xor |
| Eqv | Left | Select | Year |
This chapter provides a brief introduction and reference to the VBScript language. Although this chapter is a concise guide to the language, VBScript could easily be the subject of an entire book. One such book is Teach Yourself VBScript in 21 Days by Sams.net Publishing.
The creator of VBScript, Microsoft, maintains information on its Web site, http://www.microsoft.com. A particularly useful page for Web developers is http://www.microsoft.com/workshop.