Vbscript Free Tutorial

Web based School

Chapter 4

Creating Variables in VBScript


CONTENTS


If you've worked through the first three days, you should have a pretty good feel for what VBScript is and how it's used in a Web page to enhance its capabilities. Today begins a series of lessons that will teach you how to write VBScript code. Today, I will teach you how to create and use variables. Variables are necessary to create useful code with VBScript. You will learn how a variable is created, what can be stored within it, and how long a variable can remain in existence once you've created it. Variables are a fundamental part of any programming language, and this lesson will teach you everything you need to know about them.

I begin by explaining to you what a variable is, and then I show you how to create one. You will also learn what a variable can store, as well as how long a variable remains in existence. Then you will work with collections of variables, called arrays, which will round out your exposure to variables in VBScript. After today, you will be well versed in this fundamental concept, and you'll be ready to begin exploring more of the fundamentals of this exciting, new language.

What Is a Variable?

When users interact with computers, they usually get to some point where the computer asks them for information. That information is stored or manipulated by the computer in some way. Suppose, for example, that you want to keep a record of whether a user has clicked a button on your Web page. To keep track of this, you need to be able to store the indicator in the computer's memory so that whenever you want to see if the user has clicked on the button, you can simply check the indicator. Perhaps you want to store the number of times the user has clicked the button. In that case, you would want to store a value in memory. In any case, you need a "container" in which to store information. Programmers commonly call these containers variables.

A variable is a virtual container in the computer's memory that's used to hold information. In concept, it is much the same as a notepad. You can jot down information on the page of a notepad and return to that specific page later to remember what you wrote or modify the information. A computer program can store information in a variable and then access that information later by referring to the variable's name.

If you've ever done any programming using a language such as Visual Basic, Fortran, C, or C++, or if you've ever taken an algebra or a math class in school, you should already be somewhat familiar with variables. In most programming languages, when you create a variable, you have to tell the computer what kind of information you are going to store in it. Because some computer languages aren't very smart or don't want to risk making the wrong assumptions for you, they need to know exactly what kind of information you'd like to store. It's not enough to say, "I don't know…I just want to put stuff in this variable!" Usually, you have to say, "I want to store numbers in this variable," or "I want to store text." This means that you usually have to know ahead of time what you're going to store when you write the program. If you want to use a variable to store a person's age, for instance, you would probably first create a variable that stores numbers.

Fortunately, VBScript is very flexible about the type of information you can store. What's even better, the language is "smart" enough to let you store in the variable almost anything you want without telling it the kind of information ahead of time. There are, of course, limits to what and how much you can store (you can't store the Library of Congress in a variable because you'd run out of space), but VBScript is capable of letting you store a variety of types of information. When you create a variable in VBScript, you can assign to it numbers with or without decimal points, text, dates and times, and even objects such as ActiveX controls, which are discussed on Day 10, "An Introduction to Objects and ActiveX Controls," and Day 11, "More ActiveX Controls."

An object, in the context used in this guide, is an entity that provides specialized function to a program or Web page. You can easily manipulate object behavior by setting well-defined characteristics of the object called properties. You can also cause the object to take specific actions by calling to action specific object orders called methods. By using an object's properties and methods, you can benefit from all the capabilities an object provides without having to worry about the internal rules of how the object itself works.

How Do I Create a Variable?

When you create a variable, you have to give it a name. That way, when you need to find out what's contained in the variable, you use its name to let the computer know which variable you are referring to. You have two ways to create a variable. The first way, called the explicit method, is where you use the Dim keyword to tell VBScript you are about to create a variable. You then follow this keyword with the name of the variable. If, for example, you want to create a variable called Quantity, you would enter

Dim Quantity

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

Dim X, Y, Z

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

Quantity = 10

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

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

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

Option Explicit

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

<SCRIPT LANGUAGE="VBScript">
<!--
Option Explicit
[the rest of your code]
-->
</SCRIPT>

Note
With the beta Internet Explorer, Option Explicit was not yet fully implemented and had to be placed in the first line next to the HTML comment tag to be included without errors. The beta implementation of Option Explicit did not always explicitly force variable declaration as specified.
In some samples you may see, Option Explicit is placed next to the comment tag to prevent errors with early versions. In the final version of Internet Explorer, however, Option Explicit is fully implemented and should appear on its own line.

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

Dim Quantity

before you enter

Quantity = 10

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

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

<SCRIPT LANGUAGE="VBScript">
<!--
Quantity = 2
Quantity = Quantity + 3
-->
</SCRIPT>

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

<SCRIPT LANGUAGE="VBScript">
<!--
Quantity = 2
Quantity = Quantite + 3
-->
</SCRIPT>

In this case, the variable Quantite would be created on-the-fly, and because it's first created, it would have a value of 0. The result variable Quantity, then, would wind up being 3, not 5. If, on the other hand, you were using the explicit method of creating variables, you would enter the code as

<SCRIPT LANGUAGE="VBScript">
<!--  
Option Explicit
Quantity = 2
Quantity = Quantite + 3
-->
</SCRIPT>

which would give you a run-time error if you spelled Quantity wrong because you had not declared it first. The run-time error that results from using Option Explicit typically makes it very clear that there is a problem and leads you right away to correcting the error. On the other hand, if you didn't use Option Explicit and therefore didn't receive the run-time error, you have a much more subtle problem. You might not even notice the incorrect result, and even if you did, it would be more difficult to immediately target the source of the problem.

The other reasons that the explicit method is better are discussed later today. Almost any seasoned programmer would recommend that you use the explicit method exclusively.

When you create a variable, you must think of a name for the variable. In most cases, the name you assign to the variable makes it easy for you to recall what the variable is used for. For example, a variable named Age is much easier to recognize than a variable named X.

VBScript lets you be quite creative when you name variables, but you can't name them just anything; you have to follow a few naming rules. The first rule is that the name must begin with a letter. A variable name of 1ToMany, for example, is not allowed. Second, the variable name cannot contain a period or space. A variable named Customer Name is illegal and will produce an error. You can't use a period either because a period is used to reference properties of objects (which will be discussed on Day 10). Third, the length of a variable name cannot exceed 255 characters. Anyone adventurous enough to supply 255 characters or more to name a variable is living life a bit on the wild side anyway! You should keep the size of your variables down to a meaningful, but acceptable, level, or else your fingers are bound to get very sore.

What Can Variables Contain?

VBScript is a new product, but it is a language derived from its parent product, Microsoft Visual Basic. VBScript is essentially a subset of Visual Basic. When you create variables in Visual Basic, you have the opportunity to specify what type of data you want to store in a variable. If, for example, you want to store integers in a variable, you can declare the variable as an integer variable using the integer data type. As a result, if you try to store anything other than an integer in the variable, Visual Basic either converts the data automatically into integer format or tells you the assignment cannot be made. If you can be specific about the type of data you are storing, your code has the potential to be less error prone because you make fewer mistakes when assigning data to variables. On the other hand, it is advantageous not to worry about restricting a variable to specific types of data. Visual Basic also gives you the choice of creating variables where it doesn't matter what kind of data you want to store. This special type of variable is called a variant.

A variant is a type of variable that can store a wide variety of data types. In many programming languages, variables can only contain a specific predeclared type of information, such as integers or strings. Variants are not restricted to one type of data (such as integers, for example). You could assign an integer value to a variant in one statement and then replace that with a string value in a subsequent statement.

VBScript uses the variant as the basis for variables you create. The variant is used most often to store numbers and strings, but it can store a variety of other types of data. These data types are often called subtypes because the variant can represent them all internally. VBScript keeps track of these subtypes on its own; you usually just store whatever you want in the variable. VBScript matches the data to the best subtype and behaves accordingly. You can also override VBScript's decision of what subtype to use-you'll learn more about that later.

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

  • Boolean
  • Byte
  • Integer
  • Long
  • Single
  • Double
  • Date (time)
  • String
  • Object
  • Error
  • Empty
  • Null

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

All of the subtypes mentioned previously are summarized in the following sections so you can see what type of data can be stored in VBScript variables.

Boolean

You can set the Boolean data type to either True or False, which are represented by -1 and 0, respectively, in VBScript. This subtype is useful when working with variables where you want to determine or set a condition.

Byte

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

Integer

The integer data type is a number that cannot contain a decimal point. Integers can range from -32,768 to +32,767. The integer is one of the most common subtypes because programmers often create variables that fit the integer best. Variables used for counting, for example, are represented internally as integers. Because a great many quantities can be expressed without a decimal point and the number itself can fit within the specified range of the integer, VBScript often chooses this subtype.

Long

Variables of the long data type are also integers, but they have a much higher range, -2,147,483,648 to 2,147,683,647 to be exact. Because this data type is also an integer, you cannot use decimal points with it. Long integers are also quite common and are usually used in cases where the range of the number exceeds the smaller range of the integer. In some cases, however, the range might even exceed that of the long. Perhaps a decimal point is needed in the number. In that case, you must use the single or double data types.

Single

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

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

Double

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

Date (Time)

The date subtype is often used because it places the date in a predefined format that other functions in VBScript can act on. If, for example, you have a date variable named HireDate and you want to know what year is in the date, you can simply use the function Year(HireDate) to find it. HireDate is represented by the date subtype so that the function can retrieve the year from the variable.

String

The string data type is used to store alphanumeric data-that is, numbers, letters, and symbols. The string is another one of the most commonly used subtypes that VBScript uses to represent a variable.

Object

The object data type is a subtype used to reference entities such as control or browser objects within a VBScript application or another application. This concept will be explored further on Day 12, "Advanced Objects: ActiveX, Java, and ActiveVRML."

Error

The error subtype is used for error handling and debugging purposes. Day 17, "Exterminating Bugs from Your Script," discusses this subject.

Empty

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

Null

The null subtype refers to variables that have been set to contain no data. Unlike the empty subtype, the programmer must specifically set a variable to null. Later in this lesson, I show you examples using the null subtype.

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

Dim Item

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

Item = 23

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

Item = "Tacoma, Washington"

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

Dim Distance as Integer

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

Distance = 6

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

Distance = 6.5

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

Dim Distance

and then set the distance using

Distance = 6.5

or

Distance = 6

or even

Distance = "6 Miles"

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

Distance = 6.75
Units = " feet"

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

Result = Distance & Units

which makes Result equal to the string 6.75 feet. (Day 5, "Putting Operators to Work in VBScript," discusses working with strings in more detail.) Now suppose you were using Visual Basic 4.0. If the Distance variable were defined using the single data type and Units were defined as a string, the command

Results = Distance & Units

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

Determining the Type of Data in a Variable

Because the variants choose the best way to represent data, you usually don't need to be concerned with what subtype is used to store data in a variable. Sometimes, however, you might want to inquire of the subtype being used or perhaps change it from one data type to another.

If, for example, you set a variable equal to a decimal value, VBScript will assign the double subtype to that variable. It would not choose the integer subtype because even though an integer would take less memory than a double, the integer would chop off the decimal and would not be the most accurate representation of the number. Why doesn't VBScript choose the single subtype rather than the double? VBScript chooses the double subtype because the double data type can more accurately represent the value than the single data type. Because the double data type uses more memory and you might not need the extra accuracy that the double data type gives you, you might want to override this decision and use the single data type instead. To begin with, you need a way to determine the variable's subtype. Then you need a way to change it.

Using VarType

In order to inquire about the subtype of a variable, you need to use the VarType function. This function takes one argument: the variable name. The function then returns an integer value that corresponds to the type of data storage VBScript is using for that variable. Table 4.1 shows you the return values for each data type.

Table 4.1. VarType return types.

Internal Representation
Value
Empty
0
Null
1
Integer
2
Long
3
Single
4
Double
5
Currency*
6
Date/time
7
String
8
OLE automation object
9
Error
10
Boolean
11
Variant**
12
Non-OLE automation object
13
Byte
17
Array**
8192
* The currency data type is not supported in VBScript, but a space is reserved for it in the ordering for consistency with Visual Basic 4.0.
**The return type 8192 is used to represent arrays. In VBScript, you can only create an array of variants. If you have an array of variants, the return type would be 8192 + 12 = 8204. Arrays of other data types are not supported in VBScript, but the array is treated in this manner for consistency with Visual Basic 4.0 (where an array of integers would evaluate to 8192 + 2, for example).

Recall the earlier example that defined a variable called Distance. The example first sets the value of Distance to 6, an integer. Consider the code in Listing 4.1, which belongs to the vartype.asp Web page that can be found on this guide's CD-ROM. Notice the return values each time the VarType function is called.


Listing 4.1. Determining the internal data type of a variant.
Sub cmdTest_OnClick()

    Dim Result
    Dim Distance

    Distance = 6
    Result = VarType(Distance)            ' Result returns 2 (integer)
    MsgBox "The subtype for the variable representing 6 is " & Result

    Distance = 65535
    Result = VarType(Distance)            ' Result returns 3 (long)
    MsgBox "The subtype for the variable representing 65535 is " & Result

    Distance = 6/95
    Result = VarType(Distance)            ' Result returns 4 (single)
    MsgBox "The subtype for the variable representing 6/95 is " & Result

    Distance = 6.5
    Result = VarType(Distance)            ' Result returns 5 (double)
    MsgBox "The subtype for the variable representing 6.5 is " & Result

    Distance = "6"
    Result = VarType(Distance)            ' Result returns 8 (string)
    MsgBox "The subtype for the variable representing ""6"" is " & Result

End Sub

As you can see, the internal representation of the variable changes as the variable is assigned new data. By using the VarType function, you can find out the variable's internal data type, or subtype. In each case, the message box displays the data being stored and the subtype of the variant variable being used to store the information.

The MsgBox statement simply displays a window with the specified message to the user, like the one shown in Figure 4.1.

Figure 4.1 : A message notifying the user of a problem.

Note
Message boxes are useful for presenting information to the user that he or she needs to see immediately. The MsgBox function requires at least one argument: the string that is contained inside the message box. Day 14, "Working with Documents and User Interface Functions," covers the MsgBox function in detail.

In addition to the VarType function, VBScript provides several other functions that return True or False based on the function and the data type of the argument passed to it. The following is a list of those functions:

  • IsDate
  • IsEmpty
  • IsNull
  • IsNumeric
  • IsObject

These functions are often more convenient to use than the VarType function if you're looking for a specific data type that is listed in one of these functions. The following sections contain a brief explanation of each of the functions.

IsDate

The IsDate function requires the variable as an argument and returns the True value if the variable is a date. This function is often used to make sure the user has entered a valid date. For example, you might want to check the string a user has entered in a text box to see if the string is a valid date. The code in Listing 4.2, taken from the CD-ROM Web page isdate.asp, shows an example of one way you might use this function.


Listing 4.2. Using the IsDate function.
Sub cmdTest_OnClick()

    Dim TestDate

    TestDate = "4/1/96"

    If IsDate(TestDate) = True Then
          MsgBox TestDate & " is a valid date", 0, "Date Test"
    Else
          MsgBox TestDate & " is not a valid date.", 0, "Date Test"
    End If

    TestDate = "4/45/96"

    If IsDate(TestDate) = True Then
          MsgBox TestDate & " is a valid date", 0, "Date Test"
    Else
          MsgBox TestDate & " is not a valid date.", 0, "Date Test"
    End If

    TestDate = "Not a date"

    If IsDate(TestDate) = True Then
          MsgBox TestDate & " is a valid date", 0, "Date Test"
    Else
          MsgBox TestDate & " is not a valid date.", 0, "Date Test"
    End If

This example creates a variable to store the start date. First, the code stores a valid date in the variable, and the IsDate function checks to see if the date is indeed valid. The IsDate function returns True, and a message box appears, telling the user that the expression is a valid date. This case is shown in Figure 4.2.

Figure 4.2 : The IsDate function in action, showing a valid date.

Next, the program places an invalid date of "4/45/96" in the variable. Because April doesn't have 45 days, the date is not valid, and the function returns False. The user is told that the date is invalid. Finally, the code stores the variable with an ordinary string that is not a date, and the test is conducted once more. In this case, the variable does not contain data representing a date, and the function again returns False. The value -1 is VBScript's internal value for the True condition, and 0 is the internal value for False. However, you can refer to True and False rather than the corresponding internal values in your programs. VBScript provides these expressions for you through a special type of keyword constant. The constant is True for -1, the true condition, and False for 0, the false condition. You can use true and false to represent -1 and 0 to make your code more readable. General-purpose constants are discussed later today.

Note
A date must fall within acceptable limits to be valid, and you must use one of several predetermined formats for the date to be acceptable, such as 7/4/96, 7-4-96, July 4, 1996, and so on. The expression 7496, for example, would not be in an acceptable format for a date. When you assign a date in quotes, such as "7/6/62", this assigns it as a string variant in valid date format. If you want it to be represented internally directly with the date sub-type, you can instead assign it using the date # delimiters, as #7/6/62#.

IsNumeric

The IsNumeric function returns True if the variable is storing a number and False otherwise. Again, this function is often useful to make sure the user has entered a number. If the user has entered something other than a valid number, you can use this function to check for that condition. The example shown in Listing 4.3, isnumeric.asp, illustrates the use of IsNumeric.


Listing 4.3. Using the IsNumeric function.
Sub cmdTest_OnClick()

    Dim Value

    Value = 23

    If IsNumeric(Value) = True Then
        MsgBox Value & " is a number."
    Else
        MsgBox Value & " is not a number."
    End If

    Value = "Twenty-Three"

    If IsNumeric(Value) = True Then
        MsgBox Value & " is a number."
    Else
        MsgBox Value & " is not a number."
    End If

End Sub

In this example, the first value is indeed a number. The second case shows the variable assigned a string. Strings that spell out numbers are just that-strings. They are not interpreted as numeric values. As a result, the second test returns False.

IsEmpty

IsEmpty determines if a variable has never been assigned any values. It might be useful to use this function to see if a variable has never been used in your code. If a variable has never been used, IsEmpty returns True. The example shown in Listing 4.4, isempty.asp on the CD-ROM, demonstrates the use of this function.


Listing 4.4. Using the IsEmpty function.
Sub cmdTest_OnClick()

    Dim Value

    If IsEmpty(Value) = True Then
        MsgBox "The variable is empty."
    Else
        MsgBox "The variable contains data."
    End If

    Value = 23

    If IsEmpty(Value) = True Then
        MsgBox "The variable is empty."
    Else
        MsgBox "The variable contains data."
    End If

End Sub

In the first test, the IsEmpty function will return True because the variable has been created but not yet used. Because it hasn't been used yet, the variable is empty. Once the variable is assigned a value, the function will return False because the variable will have data assigned to it. To take a variable that has already been assigned data and wipe it from existence, you can enter the command

variable_name = Nothing

where variable_name is the name of the variable. The Nothing literal not only deletes the contents of the container, but it also eliminates the container entirely. If, after setting a variable equal to Nothing, you apply IsEmpty to the variable, the function will return True.

IsNull

Another useful condition to check is whether a variable is set to a Null value. If the Null literal has been assigned to a variable, IsNull returns True. Null empties the contents of a variable container, but it does not wipe out the container like the Nothing literal does. The example in Listing 4.5, isnull.asp on the CD-ROM, shows a useful example of this function.


Listing 4.5. Using the IsNull function.
Sub cmdTest_OnClick()

    Dim TestString

    If IsEmpty(TestString) = True Then
        MsgBox "The variable is empty."
    Else
        MsgBox "The variable is not empty."
    End If

    If IsNull(TestString) = True Then
        MsgBox "The variable is Null."
    Else
        MsgBox "The variable is not Null."
    End If


    TestString = "This is a test."

    If IsEmpty(TestString) = True Then
        MsgBox "The variable is empty."
    Else
        MsgBox "The variable is not empty."
    End If

    If IsNull(TestString) = True Then
        MsgBox "The variable is Null."
    Else
        MsgBox "The variable is not Null."
    End If

    TestString = Null

    If IsEmpty(TestString) = True Then
        MsgBox "The variable is empty."
    Else
        MsgBox "The variable is not empty."
    End If

    If IsNull(TestString) = True Then
        MsgBox "The variable is Null."
    Else
        MsgBox "The variable is not Null."
    End If

  End Sub

In this example, the variable TestString is first created. The first check is to see whether the variable is empty. Because nothing has been stored in it yet, the condition returns True, and the user sees the message box explaining that the variable is empty. Likewise, it has not been assigned a Null value at this point, so the message indicates that the variable is not Null.

Then the variable is assigned a string. The next check is to see whether the variable is empty by calling the IsEmpty function. Because the variable has been assigned data, it is not empty, and the IsEmpty function returns False. Furthermore, because the variable has been assigned a string, it is not Null either.

Finally, the string is set to Null. Even though the string has been set to Null, it is not empty, so IsEmpty returns False again. This time, the string is Null, so the IsNull function returns True.

These functions are useful in determining whether a variable has been loaded with data. The program can then make a decision based on whether a variable contains data. You will see how to do this on Day 6, "Controlling the Flow of VBScript Code."

IsObject

You use the IsObject function to see if a variable has been set to reference an object. A variable can be assigned to refer to an object with a statement such as

Set myVariable = document.MyForm

The line of code refers to document.myform. This specifies a user input form called myform contained on the current-page document. This form object is then assigned to the variable myVariable. Then subsequent statements can use the variable IsObject to verify that the variable myVariable does indeed refer to an object, as opposed to, for example, an integer or a string. You will learn more about object concepts on Days 8 through 10, beginning with "Intrinsic HTML Form Controls" on Day 8.

Changing the Type of Data in a Variable

Consider once again the example of assigning a decimal value to the Distance variable. Suppose that when you assign Distance a value of 6.5, you don't want it to take on the double data type because the single data type is faster and uses less memory. As a result, you might want to change the internal representation of the data type. You can use the set of functions shown in Table 4.2 to convert variables from one internal representation to another.

Table 4.2. Variant internal representation conversion functions.

Variant
Description
CBool Converts data to the Boolean type
CByte Converts data to the byte type
CDate Converts data to the date type
CDbl Converts data to the double type
CInt Converts data to the integer type
CLng Converts data to the long type
CSng Converts data to the single type
CStr Converts data to the string type

Suppose, for example, the user enters a value with a decimal point, but you want VBScript to convert the value to an integer instead. When the user enters the decimal value, VBScript will automatically assign the value to the double data type. You need to explicitly tell VBScript to convert the value to an integer so you use the CInt function. The example shown in Listing 4.6, called cint.asp on the CD-ROM that accompanies the guide, shows you how you could use this function to accomplish that goal.


Listing 4.6. Using CInt to make sure a value is an integer.
   Sub cmdTest_OnClick()

    Dim Result

    Result = 5.2

    MsgBox "You have entered a floating-point value of " & Result

    Result = CInt(Result)

    MsgBox "Your floating-point value has been converted to an integerÂ
              value of " & Result

End Sub

In this example, the variable named Result is stored with a value-in this case, 5.2. (Obviously, in anything other than a sample program, you'd probably obtain the result from a calculation or user input, but for simplicity, the value is assigned directly here.) The CInt function then converts the value to an integer, and the result is stored in the variable. The result displayed from the first message box is You have entered a floating-point value of 5.2. The second message box, as you probably anticipated, displays Your floating-point value has been converted to an integer value of 5, as shown in Figure 4.3.

Figure 4.3 : The Cint function in action, converting a floating-point number to an integer number.

In this sample program, the result isn't used any further. In a more realistic program, the new result would typically be used elsewhere in VBScript code or it would be presented to the user.

Each of the related conversion functions is described briefly in the sections that follow. You will see numerous examples of these functions throughout the guide.

CBool

The CBool function takes a variable and converts its subtype into the Boolean data type. Boolean values can be either True or False. Any number except zero is automatically converted to True, and zero is always converted to False. You cannot pass a string as an argument to this function. If you do, you'll get a run-time error.

CByte

The CByte function takes a variable and converts its subtype into the byte data type. In order for this function to work, the value to be converted must be a number in the acceptable range for a byte-between 0 and 255. If the number falls outside this range, a run-time error results. In addition, you cannot use strings as arguments for this function.

CDate

The CDate function takes a variable and converts its subtype into a date data type. The argument must be a string in an acceptable format for dates. If it's not, a run-time error results.

CInt

The CInt function takes a variable and converts its internal subtype into the integer format. It requires a number for its argument, and it rounds the value to the closest integer representation. If the number falls outside the range of the integer data type, a run-time error results.

CLng

The CLng function takes a variable and converts its internal subtype into the long integer format. It requires a number for its argument, and it rounds the value to the closest integer representation. If the number falls outside the range of the long data type, a run-time error results.

CSng

The CSng function takes a variable and converts the internal subtype into the single data type. The variable cannot be a string; it must be a number. Furthermore, the number must fall within the range of the single data type.

CDbl

The CDbl function takes a variable and converts the internal subtype into the double datatype. The variable cannot be a string; it must be a number. In addition, the number must fall within the range of the double data type.

CStr

The CStr function converts the subtype of a variable into the string data type. The function can take any argument, whether it's a number or even a string, and convert it automatically to a string. This function is useful when you need to create a string that contains a number and insert that number into the string.

Working with Constants

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

A constant is a variable within a program that never changes in value. Users can create their own constants by initializing variables accordingly and then not changing their value. VBScript defines the special True and False constants, as well.

Throughout this lesson, you have seen the True and False constants in action. Keep in mind that it is illegal to change the value of one of VBScript's intrinsic constants. Therefore, the statement

False = 10

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

Unfortunately, you cannot create true constants with VBScript. The language will still allow you to change the value of any constant variable you define. Many languages have ways to declare a constant so that you cannot alter its value anywhere in the program. VBScript does not offer this level of strictly enforced true constant declaration. You can simulate a constant, however, by following two rules:

  • When you create the simulated constant, name the constant with uppercase letters if the constant represents a value unique to your program. If the constant is a special value expected by VBScript, prefix the constant name with the letters vb. This naming convention is not required, but it will help you distinguish the constant from all the other variables.
  • After you assign the initial value to the variable, don't change the variable. VBScript will not enforce this for you, so you'll have to make sure you don't change the value of a simulated constant in your code.

If you wanted to create, for instance, a constant that contains your company name so you can use it throughout your code, you can use the following statements to define the constant:

Dim COMPANY
COMPANY = "Acme Enterprises"

Then use the variable throughout your code, never setting the variable COMPANY to any other value. This convention will make it easier to work with and recognize simulated constants.

Special constants you supply to VBScript functions, methods, and statements should be prefixed with vb, as previously mentioned. Table 4.3 shows these constants and the values you should assign to them.

Table 4.3. A sampler of VBScript constants.

Constant
Value
Meaning
vbOKOnly
0
MsgBox buttons desired
vbOKCancel
1
MsgBox buttons desired
vbAbortRetryIgnore
2
MsgBox buttons desired
vbYesNoCancel
3
MsgBox buttons desired
vbYesNo
4
MsgBox buttons desired
vbRetryCancel
5
MsgBox buttons desired
vbCritical
16
MsgBox icon desired
vbQuestion
32
MsgBox icon desired
vbExclamation
48
MsgBox icon desired
vbInformation
64
MsgBox icon desired
vbDefaultButton1
0
MsgBox default button desired
vbDefaultButton2
256
MsgBox default button desired
vbDefaultButton3
512
MsgBox default button desired
vbOK
1
Return code: selected MsgBox button
vbCancel
2
Return code: selected MsgBox button
vbAbort
3
Return code: selected MsgBox button
vbRetry
4
Return code: selected MsgBox button
vbIgnore
5
Return code: selected MsgBox button
vbYes
6
Return code: selected MsgBox button
vbNo
7
Return code: selected MsgBox button
vbCrLf
chr(13) & chr(10)
Causes line break in text

These constants can be defined in your VBScript code and used when needed. For example, suppose you want to use the vbCrLf constant in your program to break up your text. You could enter the code as follows:

Dim vbCrLf : vbCrLf = chr(13) & chr(10)  ' Causes line break in text
Dim svResponse

svResponse = "The password is less than twelve characters.  " & vbCrLf & _
             "Please enter the password again."

In this case, the first line of code declares and defines the constant (note the vb prefix). Then, another variable is declared and stored with the string shown above. Because the constant vbCrLf is used by VBScript to break a line of text and is not a "homemade" constant, the vb prefix is used rather than uppercase letters.

Note
A complete listing of the values shown in Table 4.3 is presented on the CD-ROM that accompanies the guide. The file constant.txt, which is located in Code\Shared\Tools, contains the declarations and assignments of each of these constants. You can then simply copy and paste the constants you want to use into your Web page. One of the advantages of using the vb naming convention for your constants-in addition to improved maintainability-is that it will make your code more compatible with standard Visual Basic for Applications code, if you ever need to move code between environments.

You'll learn more about constants on Day 13, "VBScript Standards and Conventions." For more useful conventions, refer to Day 13.

The Scope and Lifetime of a Variable

With VBScript you can create variables that are shared throughout your code, or you can create variables that are used only with code blocks called procedures. A procedure is a block of code that accomplishes a specific goal. For example, you might have a procedure that calculates the total cost of an item. Perhaps you have a procedure that is executed when the user clicks a command button. VBScript has three types of procedures: subroutines, functions, and events. Each of these will be defined and discussed on Day 7, "Building a Home for Your Code." For now, just think of a procedure as a body of code that gets executed for some reason. This section discusses a procedure that gets executed whenever the user clicks a button.

A procedure is a body of code that is called from within VBScript to be executed.

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

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

Variables not only have a scope, but they also exist for different amounts of time depending on their scope. This property of a variable is often referred to as its lifetime. Script-level variables are created outside of any procedures using the Dim keyword. They exist from the time the variable is declared until the time the script is finished running. Listing 4.7 shows an example of a script-level variable. This Web page, named scrptlvl.asp, is on the CD-ROM that accompanies the guide.


Listing 4.7. Using script-level variables.
<HTML>

<TITLE>Using Script-Level Variables</TITLE>

<H1><A HREF="http://w3.softlookup.com"><IMG  ALIGN=BOTTOM
SRC="../shared/jpg/samsnet.jpg" BORDER=2></A>
Using Script-Level Variables</H1>

<BODY>

<HR>

<CENTER><INPUT TYPE=BUTTON VALUE="Click Me" NAME="cmdTest"></CENTER>

<HR>

<center>
from <em>Teach Yourself VBScript in 21 Days</em> by
<A HREF="../shared/info/keith.asp">Keith Brophy</A> and
<A HREF="../shared/info/tim.asp">Tim Koets</A><br>
Return to <a href="..\default.asp">Content Overview</A><br>
1996 by SamsNet<br>
</center>

<SCRIPT LANGUAGE="VBScript">
<!--  
Option Explicit

   Dim Counter

   Sub cmdTest_OnClick()
      SetCaption
      cmdTest.Value = Counter
   End Sub

   Sub SetCaption()
      Counter = Counter + 1
   End Sub

-->
</SCRIPT>

</BODY>

</HTML>

Note
The code in Listing 4.7 makes use of the following HTML button control definition:
<INPUT TYPE=BUTTON VALUE="Click Me" NAME="cmdTest">
HTML form controls are one of several types of controls you can place on a Web page and manipulate using VBScript. These controls will be discussed in detail on Day 8. In this example, all you need to know about the button declaration is that it results in the display of a button on the form. This internal name of the button, which is visible to the VBScript application, is cmdTest. VBScript can assign or retrieve values from this button by referencing its caption with a statement like the following:
Variable1 = cmdTest.Value
When the user clicks the button, the browser informs VBScript that an OnClick event has occurred for that given button. VBScript will begin the routine cmdTest_OnClick if that procedure exists.

In Listing 4.7, the variable, which is called Counter, is declared outside all the procedures in the script. As a result, any of the procedures within the script can use it. When the user clicks the cmdTest button in the Web page, the browser must handle the OnClick event that occurs. The procedure cmdTest_OnClick is called because it is associated with the button by virtue of its name. The first action of this procedure is to call SetCaption. The SetCaption procedure increments the counter variable by 1 and ends. Then the procedure that called SetCaption continues by setting the text on the command button equal to Counter. This, in effect, increments the number on the command button each time it is clicked, as shown in Figure 4.4.

Figure 4.4 : Script-level variables are used here to increment a value that appears on the button on the Web page.

Because the variable is shared among all the procedures in the script, SetCaption doesn't need to be told the value of Counter; it can simply look for it itself.

What would happen if the variable were moved inside the calling procedure rather than outside, as is the case in the Web page incorvar.asp on the CD-ROM, shown in Listing 4.8?


Listing 4.8. Using procedure-level variables incorrectly.
<SCRIPT LANGUAGE="VBScript">
<!--  
Option Explicit

   Sub cmdTest_OnClick()
      Dim Counter
      SetCaption
      cmdTest.Value = Counter
   End Sub

   Sub SetCaption()
      Counter = Counter + 1
   End Sub
-->
</SCRIPT>

Because of the Option Explicit command at the beginning of the script, running this code would result in an error! The Counter variable has been moved from outside the procedures into the cmdTest_OnClick procedure, so it is only available to that procedure. The SetCaption procedure no longer has access to the variable, so it would have to declare Counter before it could use it. Because Option Explicit is being used, VBScript does not recognize the variable without an explicit declaration, and an error results. Listing 4.9, inappvar.asp, shows the fix for this error condition.


Listing 4.9. Using procedure-level variables inappropriately.
<SCRIPT LANGUAGE="VBScript">
<!--  
Option Explicit

   Sub cmdTest_OnClick()
      Dim Counter
      SetCaption
      cmdTest.Value = Counter
   End Sub

   Sub SetCaption()
      Dim Counter
      Counter = Counter + 1
   End Sub

<--
</SCRIPT>

Now the code will run, but it still won't work right. Because each procedure has its own copy of the variable, they can't share with each other. When the SetCaption procedure is called, it creates the Counter variable and sets it equal to 1. Then, when the calling function resumes, it uses its own copy of Counter, which has never been set. The result is that nothing at all is displayed in the command button when it is clicked, as can be seen in Figure 4.5.

Figure 4.5 : Here, a procedure-level variable is used and results in an unintended loss of data-the caption of the button is empty!

Sometimes, you might want to use two different copies of a variable. Consider Listing 4.10, dim.asp, for example.


Listing 4.10. Creating procedure-level variables with Dim.
<HTML>

<TITLE>Script-Level Variables</TITLE>

<H1>
<A HREF="http://w3.softlookup.com"><IMG  ALIGN=BOTTOM
SRC="../shared/jpg/samsnet.jpg" BORDER=2></A>
Script-Level Variables
</H1>

<BODY>

<HR>

<CENTER><H2>Using a script-level variable properly</H2>
<INPUT TYPE=BUTTON VALUE="Go!" NAME="GoButton">
<INPUT TYPE=BUTTON VALUE="You haven't clicked on Go yet!"
NAME="TestButton"></CENTER>

<HR>

<center>
from <em>Teach Yourself VBScript in 21 Days</em> by
<A HREF="../shared/info/keith.asp">Keith Brophy</A> and
<A HREF="../shared/info/tim.asp">Tim Koets</A><br>
Return to <a href="..\default.asp">Content Overview</A><br>
1996 by SamsNet<br>
</center>

<SCRIPT LANGUAGE="VBScript">
<!--  
Option Explicit

   Dim Action

   Sub GoButton_OnClick()
      Action = 1
   End Sub

   Sub TestButton_OnClick()
      If Action = 1 Then
         SetCaptionA
      Else
         SetCaptionB
      End If
   End Sub

   Sub SetCaptionA()
      Dim MyString
      MyString = "You've clicked on Go!"
      TestButton.Value = MyString
   End Sub

   Sub SetCaptionB()
      Dim MyString
      MyString = "You haven't clicked on Go yet!"
      TestButton.Value = MyString
   End Sub

-->
</SCRIPT>

</BODY>

</HTML>

In this example, you have two command buttons on a Web page, as shown in
Figure 4.6.

Figure 4.6 : The initial state of the dim.asp Web page.

When the first command button, called GoButton, is clicked, a procedure runs that sets a script-level variable called Action equal to 1. When the second button, TestButton, is clicked, a procedure runs that checks the value of Action and calls either SetCaptionA or SetCaptionB, depending on the value of Action. Figure 4.7 shows what happens after the user clicks the GoButton command button.

Figure 4.7 : The dim.asp Web page after the user has clicked on the Go! command button.

Both SetCaptionA and SetCaptionB create their own local copies of MyString and set the caption of TestButton with their respective strings. Both strings have the same name, but they are separate copies. As soon as each procedure ends, its own copy of MyString is destroyed.

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

You should know one more thing about variables. Suppose you create a script-level variable called MyVariable, and then you create a procedure-level variable with the same name, as shown in Listing 4.11! This Web page is named dupvar.asp and, like the others, is on the CD-ROM that comes with this guide.


Listing 4.11. Creating duplicate variables at different scopes.
<HTML>

<TITLE>Variable Scope</TITLE>

<H1><A HREF="http://w3.softlookup.com"><IMG  ALIGN=BOTTOM
SRC="../shared/jpg/samsnet.jpg" BORDER=2></A>
Variable Scope</H1>

<BODY>

<HR>

<CENTER><H2>Creating duplicate variables with different scopes</H2>
<INPUT TYPE=BUTTON VALUE="Click Me" NAME="cmdTest"></CENTER>

<HR>

<center>
from <em>Teach Yourself VBScript in 21 Days</em> by
<A HREF="../shared/info/keith.asp">Keith Brophy</A> and
<A HREF="../shared/info/tim.asp">Tim Koets</A><br>
Return to <a href="..\default.asp">Content Overview</A><br>
1996 by SamsNet<br>
</center>

<SCRIPT LANGUAGE="VBScript">
<!--
Option Explicit

   Dim MyVariable

   Sub cmdTest_OnClick()
      Dim MyVariable
      MyVariable = MyVariable + 1
      cmdTest.Value = MyVariable
   End Sub
-->
</SCRIPT>

</BODY>

</HTML>

If you create duplicate variables, VBScript will create two copies and use only the procedure-level variable in the procedure. It will not use the script-level variable. In Listing 4.11, two copies of MyVariable are created. Unfortunately for this programmer, the copy that gets used inside the procedure is not the one he would like to see used. If he removes the second Dim MyVariable that is inside the procedure, the code will increment the value every time the button is clicked. As it is now, MyVariable will be created locally every time the procedure is executed and will always be equal to 1, as shown in Figure 4.8.

Figure 4.8 : The dupvar.asp Web page with a button caption always set to 1.

VBScript uses the variable with the smallest scope whenever there are duplicates. This might seem confusing, and it is. The best way to avoid this situation is to make sure you never give variables in your program the same name unless they are procedure-level variables residing in two separate procedures, as in the example in Listing 4.10.

Working with Arrays

So far today, you've learned what a variable is, how to create one, and what you can store inside one. You might be wondering if there is some easy way to group variables together in a set. For example, you may have a Web page that requests many of the same things-such as a list of screen coordinates-and you want to store those coordinates together. Rather than create ten separate variables, you can instead create one variable that holds all ten pieces of data. This type of container is called an array.

An array is a type of variable that ties together a series of data items and places them in a single variable.

Arrays are useful when you're storing sets of similar data because they often make it easier to manipulate the data together. If you wanted to manipulate a list of ten coordinates, you would have to execute ten different statements to handle each one. Besides, how can you be sure you have ten? What if you have only six at the moment? How can your code handle this kind of situation where you really don't know ahead of time how many pieces of information you have? Here is where the array comes to the rescue!

The beauty of an array is that it enables you to store and use a series of data using one variable name and an index to distinguish the individual items. By using an index, you can often make your code simpler and more efficient so that it's easier for you to put a script together and change it later. With VBScript, the elements inside your array can hold any kind of data. The elements don't have to be all integers or all strings, for example. The array can hold a combination of data types.

Creating Arrays

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

Fixed-Length Arrays

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

Dim Array_Name(count - 1)

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

Dim Names(19)

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

The index of the array always starts at 0 and ends at count -1. In the case of the Names array, the number of containers, or elements, in the array ranges from Names(0) to Names(19) for a total of 20 elements. To see how this works, look at the code in Listing 4.12. The complete Web page that executes this code is on the CD-ROM with the title index.aspl. This simple code listing sets every element of the Names array equal to the string "Unknown". This is similar to putting the same type of shoe in every shoe box in your closet.


Listing 4.12. Working with the index of an array.
Dim Names(19)
Dim i

For i = 0 to 19
    Names(i) = "Unknown"
Next

This code listing uses a loop to set each element. Essentially, the program treats the variable i like a counter and keeps incrementing it by 1 all the way from 0 to 19. The Names(i) = "Unknown" code statement is executed 20 times, and each time the i value is different. Day 6 covers loops in depth.

It's important to remember that the first container in your array has an index of 0, not 1. In this example, the first element in the array is Names(0), not Names(1). If you forget this and start with Names(1), you'll only be able to use 19 of the containers, not 20.

Dynamic Arrays

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

Dim Names()

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

ReDim Array_Name(Count - 1)

So, if you enter

ReDim Names(9)

you will create an array that has room to store ten elements. This way, you can set the size of the array while the code is running rather than when you write the code. This can be useful when the user gets to decide how many names he will enter. For example, he might type the number of names he's going to give you into a text control. In that case, you could use code like what's shown in Listing 4.13. This Web page is called dynamic.asp and is on the CD-ROM that comes with the guide.


Listing 4.13. Working with a dynamic array.
Dim Names()
Dim i
Dim Count

Count = txtCount.Value

ReDim Names(Count - 1)

For i = 0 to Count - 1
   Names(i) = "Unknown"
Next

MsgBox "The Names array has just been dimensioned to " & _
Count & " elements and set with the string ""Unknown""."

In this case, the number of elements is set using the variable Count instead of some fixed number. This code isn't very safe, of course, because the user might not enter a valid number, or for that matter, he might type in something strange like the name of his dog. In Day 17, you will see how to handle those kinds of situations by making your scripts as "dummy proof" as possible.

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

The Preserve keyword is very important when using ReDim. Suppose, for example, that you create a dynamic array, specifying its storage space by using ReDim, fill it with data, and then later decide to make it larger so you can fill it with more information without losing your original data. (See Listing 4.14.) The Web page is saved on the CD-ROM as nopresrv.asp.


Listing 4.14. Resizing a dynamic array without Preserve.
Dim Names()
Dim i
Dim Count

Count = txtCount.Text

ReDim Names(Count -1)

For i = 0 to Count - 1
    Names(i) = "Unknown"
Next

ReDim Names( Count + 49)

For i = Count to Count + 49
    Names(i) = "Extra Names"
Next
MsgBox "The Names array has just been dimensioned to " & Count & _
      " elements and redimensioned with an additional 50 elements."

In this example the programmer has declared an array of size Count and then resized the array to 50 plus the original size. (You probably noticed that 49 is used instead of 50 in the ReDim statement. Keep in mind that because the array index starts at 0 rather than 1, you set the size to be the desired Count - 1.) The problem is that without the Preserve keyword after the ReDim statement, the first Count elements are erased.

Now consider the code in Listing 4.15. This listing is based on the Web page titled preserve.asp located on the CD-ROM that accompanies the guide.


Listing 4.15. Resizing a dynamic array with the use of Preserve.
Dim Names()
Dim i
Dim Count

Count = txtCount.Text

ReDim Names(Count-1)

For i = 0 to Count - 1
    Names(i) = "Unknown"
Next

ReDim Preserve Names(Count + 49)

For i = Count to Count + 49
    Names(i) = "Extra Names"
Next
MsgBox "The Names array has just been dimensioned to " & Count & _
       " elements and redimensioned with an additional 50 elements. _
       All items retain their original values."

If you use Preserve after the second ReDim statement, as shown in Listing 4.15, VBScript will still retain the first Count elements. This is like adding shoe boxes to a closet without emptying the boxes already in the closet.

If you want to erase whatever is in the array when you resize it, leave off the Preserve keyword. If you want to keep what you've got, make sure to include it when you re-dimension an array.

You can use the ReDim statement again and again in your procedure. Suppose you want to change the size of the array twice in the procedure. You might have a Web page where the user enters two sets of names for a couple sports teams. You could have code similar to the Web page redim.asp, whose VBScript code is shown in Listing 4.16.


Listing 4.16. Working with a dynamic array and ReDim.
Sub cmdTest_OnClick()

      Dim Names()
      Dim i
      Dim Green_Count
      Dim Red_Count

      ' Initialize the values
      Green_Count = 0
      Red_Count = 0

      Green_Count = txtGreenCount.Value

      ReDim Names(Green_Count - 1)

      For i = 0 to Green_Count - 1
         Names(i) = "Green Team Player"
      Next

      Red_Count = txtRedCount.Value

      ReDim Preserve Names(Green_Count + Red_Count - 1)

      For i = Green_Count to Green_Count + Red_Count - 1
         Names(i) = "Red Team Player"
      Next

      MsgBox Green_Count & " Green team members and " & Red_Count & _
                           " Red Team members have been created."

End Sub

As you can see, ReDim is used here (along with Preserve) to dimension the array the first time and then later to make it larger.

Determining the Size of the Array

In the course of working with arrays, you might want to find out how large an array is. VBScript provides you with a function called UBound, which gives you the information you need. UBound tells you how many boxes of shoes you have set aside in the closet. This function returns an integer value and requires one argument-the array:

size = UBound(array_name)

where size is a variable that will contain the bound value of the array and array_name is the name of the array. To see how you can take advantage of these functions, compare Listing 4.12 to the Web page named ubound.asp, whose VBScript code is shown in Listing 4.17.


Listing 4.17. Using UBound on a fixed-length array.
Dim Names(19)
Dim i

For i = 0 to UBound(Names)
    Names(i) = "Unknown"
Next
MsgBox "The upper bound of the Names() array is " & UBound(Names)

In this example, you use UBound(Names) instead of 19. This might seem trivial, but what happens if you want to change the size of your array from 20 elements to 40? You would not only have to change the declaration of the array, but you'd also have to find every place in your code where you reference the size of the array and change the values. By using the bounding function, you only have to make one change, which makes your code easier to maintain.

Multi-Dimensional Arrays

The arrays you have seen so far today have had only one dimension. Using the shoe box analogy, it's like having a closet full of shoe boxes. Suppose that you not only want to put your shoes on shelves, but you also want to put your work shoes on one specific shelf, your dress shoes on another, and so on. If you did that, each shoe box "address" would first refer to the shelf and then to the particular box on that shelf.

When writing VBScript code, you might want to create an array in a similar way. You can do this by creating an array with more than one dimension, making it a multi-dimensional array. With VBScript, you can define up to 60 dimensions for a single array. How could this be useful? Suppose that you have a grid like a spreadsheet on your Web page, and you want to give the user the ability to enter data in each cell. You could keep track of the grid using a two-dimensional array by declaring the array as

Grid(rows - 1, columns - 1)

where rows is the number of rows on the spreadsheet and columns is the number of columns. If you wanted to obtain the value stored in row two, column three, you could use the statement

Value = Grid(2 - 1, 3 - 1)

to obtain the information. Notice that you have to decrease the index by 1 because the index starts with 0. Also, when you use the ReDim statement to re-dimension a multi-dimensional array, you can change the limit of any of the dimensions, but you cannot change the number of dimensions. For example, if you have declared the array

Dim Grid()

and you dimension the array as

ReDim Grid(10, 30)

you can execute another ReDim statement like

ReDim Grid(5, 100)

but you cannot add another dimension:

ReDim Grid(5, 10, 20)

The first ReDim statement you enter in a procedure sets the number of the dimensions of the array. After that, you cannot change the number of dimensions; you can change only the number of elements for that dimension.

Changing the Contents of the Array

One final word about arrays: You can clear the contents of an array entirely by using the Erase function. This function takes one parameter, the name of the array. If you want to erase an array out of memory, simply enter

Erase Array_Name

Not only will this erase the array's contents, but with dynamic arrays (those declared with ReDim), it will also free the memory that was used by the array. Because variables and large arrays in particular can take a lot of memory, it is wise to use the Erase statement whenever you're finished with an array in a procedure.

Summary

Today, you got the information you need to create and use variables within your VBScript code. It is one of several key lessons that get you up to speed on the basics of VBScript. If you've used Visual Basic or some other programming language, parts of this lesson might seem quite elementary to you. It is important, however, to get a survey of variable use in VBScript because each language has a different way of approaching variable creation and use.

Today's lesson begins by giving a definition of what a variable actually is-a container in which to store information. Then you saw how easy it is to create a variable by simply entering Dim followed by the name of the variable in your code. This lesson also describes all the various kinds of data you can place in a variable.

You have seen how VBScript figures out what kind of data you have stored in a variable. This is important because you sometimes need to know what VBScript thinks you have stored just in case you want to change its mind. You have learned about a series of functions you can use, if necessary, to ask VBScript about the internal representation of a variable. In this way, you can make sure the user has entered data correctly, or you can decide how to handle data based on how it is being stored. You then saw a group of functions that convert the internal data representation from one type to another. This is often useful when you want to change the format of the data in order to manipulate it with other variables.

Today's lesson also discusses the scope and lifetime of variables, pointing out that you can use Dim to create a procedure-level variable whose contents are erased once a procedure ends or you can declare a variable outside a procedure, making it a script-level variable that all the procedures can share within a script. That way, a variable can exist no matter what code the VBScript procedure is executing.

Having discussed simple variables, the lesson concludes by discussing arrays. Arrays are useful, powerful, and time-saving. You have seen how to create both a fixed-size array and a dynamic array. You have also seen how to re-dimension a dynamic array and preserve the contents of the array while doing so, how to create arrays of more than one dimension, and how you might use such arrays.

You've made it through the first day that teaches you how to write VBScript code! As you learn more about VBScript and its capabilities, all the concepts you are learning now will not only start to make more sense, but you will also begin to use VBScript in increasingly more powerful ways. A few days from now you'll be well along your way, developing powerful and fun Web pages. You can't get there without first learning the fundamentals, and this is the first lesson where you do just that. In tomorrow's lesson, you will learn how to put variables to use with operators. Day 5 is also when you will learn how to use arithmetic with your variables, compare one variable to another, set the contents of variables, and work with strings. Then, on Day 6, you will learn how to control the flow of your code and create procedures. Day 7 gets into more details on procedures, and on Days 8 and 9, you'll learn about the intrinsic HTML controls. Then, when you reach Day 10, you'll be ready to learn the powerful ActiveX controls.

Q&A

Q
Why doesn't VBScript support all the other data types that Visual Basic supports?
A
I can't speak for Microsoft, but they probably dropped the other data types to keep the language simple. A likely goal for the VBScript design team was to make the language as flexible, easy to learn, and safe to use as possible. The variant type is definitely the easiest to use, and it reduces the size and complexity of the VBScript run-time interpreter. This makes VBScript faster and more efficient at what it does.
Q
Why would I ever need to figure out the subtype of a variable?
A
Usually, you won't have to worry about variable subtypes. On occasion, however, you may need to inquire as to a variables subtype so you can convert it into another format or carry out a certain action depending on the variable. For example, you may want to execute code differently if the user enters None in a text box versus a value.
Q
Arrays look pretty complicated. Will I ever need to use them?
A
They might seem complicated to you now, but you will see as you work through this guide that not only are they easy to use, but they can also save you a great deal of extra code and make your program a lot easier to write and understand later.

Workshop

Today you saw a Web page that makes use of simple variables. Take one of the code examples in this lesson and create your own Web page. Once you've got it running, create several variables and assign data to them. Practice displaying the contents of those variables on the Web page using MsgBox and the form button control I have discussed.

Quiz

Note
Refer to Appendix C, "Answers to Quiz Questions," for the answers to these questions.

  1. What data type are VBScript variables based on? Can you remember the data types you can store inside a variable?
  2. Write the code required within a procedure to create a variable for storing your name with VBScript code. Assign your name to that variable.
  3. Assume you have a variable called Age that contains an age provided by the user. Write the code that ensures that the user has entered a number as her age. If the user hasn't entered a number, tell her she needs to enter her age correctly.