Previous Page TOC Next Page



- 20 -
Introduction to VBScript



What Is VBScript?


Yesterday you learned how to use JavaScript in your Web pages. I also mentioned 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 is automatically interpreted and run.

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 to VBScript because Netscape has such a large user base. Supposedly, however, other browser vendors are planning to license VBScript from Microsoft and incorporate it into their browsers soon.

Today you will learn how to successfully implement the VBScript programming language into your HTML files. This chapter should also serve as a convenient reference to the VBScript language in your future programming projects.

A Simple Example


First 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 will prompt the user for his or her name and then display 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 20.1 shows the input prompt. Figure 20.2 shows the output to the screen after the name was entered.



You might notice that a lot of the examples presented today are the same as the ones presented yesterday while you were learning JavaScript. This will help you to better compare and contrast the two languages.

Figure 20.1. A simple VBScript example (before entering a name).

Figure 20.2. A simple VBScript example (after entering a name).

The preceding example displays a prompt with the InputBox function. The value obtained is stored in a variable called name. The variable is then combined with other text and displayed in the browser's window using the Document.Write method.

Now that you have seen a little of the functionality available through VBScript, you will continue with a tutorial of the language itself.

Differences Between VBScript and Visual Basic


As mentioned, VBScript is a subset of Visual Basic. There might be readers who are very familiar with Visual Basic and simply need to know what Visual Basic features are not available in VBScript. This section will briefly discuss the major differences between the two. Readers who are unfamiliar with Visual Basic might want to skip ahead to the next section titled "The <SCRIPT> Tag."

The following list identifies the most significant features of Visual Basic that are not supported by VBScript:

As you might notice, most of the exclusions from VBScript were 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.

The <SCRIPT> Tag


The <SCRIPT>. . .</SCRIPT> pair of tags tell the browser that a script is enclosed. The <SCRIPT> tags can appear either in the <HEAD> or <BODY> section of the HTML file. The advantage of placing it in the <HEAD> section is that it 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>


You might have noticed that the comment is not enclosed in normal <- and -> tags for HTML comments. This is because VBScript supports the same style comments 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. This will hide the VBScript from older browsers that don't support it, for 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 will not include the script hiding feature; this will help 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.

Data Types


Like JavaScript, VBScript is a loosely typed language. This means 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:

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 the preceding 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.

Variables


As you have seen in the examples so far, VBScript supports the use of variables. 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, such as the following example:




Dim myvariable

Multiple variables can be declared together if you separate each variable name by a comma, as shown in the following example:




Dim myvariable, x, y, AVeryLongVariableNameWithANumberInIt8


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 simply be placed at the beginning of VBScript code. This will ensure that the variable names you have chosen are spelled consistently throughout your program because 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 for as long as the script is running. A local variable is declared inside a procedure or function and can only be accessed in that procedure or function. In addition, local variables only last as long as you are executing that procedure.

Literals (Constants)


Literals are values in a program that don't change; they are constant. In VBScript there isn't a CONST statement like in Visual Basic that can be used to represent some constant value. In VBScript, this is done by using a variable.

Expressions


A set of literals, variables, and/or operators that evaluates to a single value is an expression. The single value can be either a string, a number, or a Boolean value. There are essentially four types of expressions in VBScript:


Arithmetic


An expression that evaluates to a number is an arithmetic expression. For example,




( 3 + 4 ) * (84.5 / 3)

would evaluate to 197.1666666667.

String


An expression can also evaluate to a string. Literal strings are enclosed in double quotes. For example:




"The dog barked " & barktone & "!"

might evaluate to The dog barked ferociously!.

Date


A date can also be used in an expression. To assign a literal date to a variable, enclose the date in # characters. The variable containing the date can then be used in a date 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 the preceding code is




In 5 days it will be 8/22/96

This capability, combined with the many date functions in VBScript, make working dates very easy. The VBScript date functions are covered in Appendix F (VBScript Language Reference).

Logical


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 is




temp > 32

This expression might evaluate to true or false, depending on the value of temp.

Arrays


Unlike JavaScript, the VBScript language has direct support for arrays. This section assumes that you already have a basic understanding of arrays.

Unlike C, C++, and Java, VBScript uses the parentheses for initializing and accessing an array. In C, C++, and Java the square brackets are used.

Declaring arrays is very similar to declaring other types of variables. To declare in array, you simply 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 zero. The feature of Visual Basic that allows you to declare arrays with a lower bound other than zero is not supported in VBScript.

To access an array element, you use the variable name followed by the element in parentheses. For example, to reference the fifth element you would use the following:




monthlySales(4)

Multiple dimension arrays are supported in VBScript. Up to 60 dimensions can be used. To declare a multi-dimension array you add an upper bound parameter for each dimension separated by commas. For example, consider the following three-dimensional array declaration:




ThreeDCoord(99,99,99)

VBScript also supports dynamic arrays with the ReDim statement. In order for an array to be declared as dynamic it must initially be declared without upper bounds, such as 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 re-dimensioned 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 monthlySales(23)



' The monthlySales(7) value is preserved



' and the array is enlarged to 24 elements



ReDim montlySales(35)



' All montlySales contents are lost since Preserve was not used

Operators


The operators available in VBScript can be categorized as follows:


Assignment Operator


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

Comparison Operators


The purpose of a comparison operator is to compare two operands and return true or false based on the comparison. The following comparison operators are supported by VBScript:


Arithmetic Operators


In addition to the standard operators (+, -, *, /) for addition, subtraction, multiplication, and division, VBScript supports the following additional arithmetic operators:

num^exp—The exponentiation operator will raise num to the power of exp.


String Operator


VBScript has a special operator that is used for concatenating (or combining) strings:


Logical Operators


VBScript supports the following logical operators that return a Boolean value:

expr1 Imp expr2 = result
False Imp False = True
False Imp True = True
True Imp False = False
True Imp True = True
Null Imp False = Null
Null Imp True = True
False Imp Null = True
True Imp Null = Null
Null Imp Null = Null

Bitwise Operators


If two numeric expressions are used with the logical operators previously defined, a bitwise comparison will be performed. The following operators are supported:

1 Imp 1 = 1


Statements


The statements that are available in VBScript can be grouped into the following categories:


Conditional Statements


Conditional statements provide the ability for a program to make a decision and perform specific actions based on the result of that decision. VBScript provides two types of conditional statements:


If. . .Then. . .Else

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 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.

The following is an example:




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 the following simple comparison:




If myVar = True Then yourVar = false

Select Case

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


Loop statements provide a means for looping through a section of code until an expression evaluates to true. VBScript provides three different types of loop statements:


For. . .Next

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 equals 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 simply placing one or more Exit For statements inside the loop.




For var = init To final [Step step]



' statements to execute while looping



  [Exit For]



Next

The following is an example:




For x=0 To 10 Step 2



   y = x * 25



   Document.Write "x=" & x & " y=" & y & "<BR>"



Next

The preceding example will loop through the code until x is equal to 10. The output can be seen in Figure 20.3.

Figure 20.3. A For. . .Next loop example.

While. . .Wend

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

The following is an example:




x = 0



While x <= 10



  y = x * 25



  Document.Write "x="& x & " y=" & y & "<BR>"



  x = x + 2



Wend

The preceding code will produce the same result as the For loop example in Figure 20.3.

Do. . .Loop

The Do. . .Loop provides several different forms, with the differences being in how the loop is exited. The loop can be exited by 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.

The Do Loop can be used with either the While condition or the Until condition. The syntax of each is shown in the following examples:




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, but the same result will be obtained as shown in the following example:




Do



' statements to execute while looping



Loop [Until|While]

The following two Do loop examples show the use of the Do loop using the Until condition (Listing 20.1) and the While condition (Listing 20.2):

Listing 20.1. A Do. . .Until Example




<HTML><HEAD>



<TITLE>A Do...Until Example</TITLE>



<SCRIPT LANGUAGE="VBScript">



dim x



x = 0



Do 



   y = x * 25



   Document.Write "x=" & x & " y=" & y & "<BR>"



   x = x + 2



Loop Until x > 10



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

Listing 20.2. A Do. . .While Example




<HTML><HEAD>



<TITLE>A Do...While Example</TITLE>



<SCRIPT LANGUAGE="VBScript">



dim x



x = 0



Do While x <= 10



   y = x * 25



   Document.Write "x=" & x & " y=" & y & "<BR>"



   x = x + 2



Loop 



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

The two preceding examples will produce the same result as the For. . .Next loop and the While. . .Wend loop examples in Figure 20.3.

Procedures


A procedure is a set of statements that can be called as needed from your main code or from other procedures. VBScript supports the use of two types of procedures: Sub and Function. A Sub procedure does not have a return value while a Function procedure 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.

Sub Procedure


The following syntax is used to define a Sub procedure:




Sub SubName([param1][,param2]…[,paramN])



   ' sub procedure statements



End Sub

In order to call this procedure, you would use the following syntax:




SubName [param1][,param2]…[,paramN]

The following example will show 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>

The output from the preceding example is shown in Figure 20.4.

Figure 20.4. An example of a Sub procedure.

Function Procedure


The syntax for a function is very similar to that of a Sub 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 is




returnVar = fnName([param1][,param2]…[,paramN])

The following example will show 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 exactly the same as the output from the Sub example in Figure 20.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 "



Document.Write AreaOfCircle(4) & " cm<SUP>2</SUP>.<BR>"



Document.Write "A circle of radius 6 cm has an area of "



Document.Write AreaOfCircle(6) & " 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>

Built-In Functions


VBScript contains a wide select of built-in functions. In order to organize all of these functions, it is useful to categorize them as follows:

A reference for all of the VBScript built-in functions is included in Appendix F.

Events


VBScript is an event-driven language. An event-driven program can respond to certain events, such as a mouse click or the loading of a document. An event can cause a section of code to execute (known as an event handler) to allow the program to respond appropriately.

Event Handlers


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 will call the CheckAge Sub when the text field is changed:




<INPUT TYPE=TEXT NAME="AGE" onChange="CheckAge">

The eventHandler code does not have to be a procedure; it can be a single VBScript statement. Because only a single statement can be used and because 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 to be sure that a valid age was entered. If not, a message will appear asking the user to re-enter the value. The event handler is called when the AGE field is changed and the focus is moved to another field. The screen output is shown in Figure 20.5.




<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="Sking">



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 20.5. A VBScript event handler example.

VBScript Object Model


The object hierarchy for VBScript is very similar and compatible to the JavaScript object hierarchy. The primary difference is that there is not a 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.

See Appendix E for descriptions of each object and its associated properties, methods and event handlers. As mentioned, each of these objects apply equally to VBScript except for the Math, String, and Date objects.

Conclusion


Today you were exposed to a brief introduction and reference of the VBScript language. Although this chapter is essentially a complete, concise guide to the language, VBScript could easily be the subject of an entire book. At the time of this writing, the author is not aware of any books that focus solely on VBScript programming. However, there will likely be many to choose from in the near future, probably even by the time this book is printed.

The creator of VBScript, Microsoft, maintains information on their Web site:

http://www.microsoft.com

A particularly useful page for Web developers is

http://www.microsoft.com/workshop

Tomorrow, you will expand your knowledge of both VBScript and JavaScript as you learn to use these scripting languages to control applets and ActiveX controls.

Q&A


Q: If VBScript is only supported by Microsoft Internet Explorer, why would I want to use it instead of JavaScript?

A: The lack of broad browser support for VBScript is definitely a serious disadvantage. This is especially true since it is not supported by Netscape Navigator. However, if you are developing an intranet application and you know that everyone in your company uses Internet Explorer, VBScript might be a wise choice. This is especially true if you are already familiar with Visual Basic.

Q: Visual Basic has a wide range of built-in financial functions. Are these available for me to use in my VBScript programs?

A: Unfortunately, the financial functions are not available to VBScript.

Q: Are the file I/O functions that are in Visual Basic available in VBScript?

A: As you can probably imagine, there would be serious security issues if the file I/O functions of Visual Basic were available in VBScript. If these functions were available, a Web programmer could read, write, and even delete data on the user's hard disk. Because of these reasons, VBScript, like Java applets, do not have user file access functionality.

Previous Page Page Top TOC Next Page