In this chapter you learn about:
Variables can be used to store a variety of information for processing by your application.
Understanding variable data types and how they affect the information stored within a variable is important.
How to declare variables, assign values to them, and use operators to interact with them is covered here.
You must ensure that the code you produce is clearly understood and easy to maintain.
There are several benefits of using arrays in program development.
Anyone who has taken algebra or geometry is already familiar with the concept of a variable. Do you remember Pythagorean's Theorem, which describes the relation of the hypotenuse to the other two sides of a right triangle? The equation is c2 = a2 + b2, where a and b are the legs of the triangle and c is the hypotenuse. You substitute the length of the sides in the variables a and b and then calculate the value of the hypotenuse, c, from the formula (a2 + b2 )½. When you assign values to a and b, you are assigning those values to variables that you then use to perform the operation to get the result. The same basic idea of assigning a value to a variable in geometry applies to variables in VBScript development as well.
Active Server Pages programs, and specifically the VBScript embedded within them, are defined by commands and the data that those commands act on. Data is broken into variables and constants. When you declare or instantiate a variable, you are setting aside (reserving) a place in memory for a value that changes over the life of the variable. A constant declaration also reserves memory, but for a value that does not change during the life of the variable. The life of a variable is defined by its scope (more on scope later in the section "Examining the Lifetime of a Variable").
Variables have two characteristics that define their existence-a data type and a variable name. In the following sections you examine each of these characteristics, leaving you with a complete understanding of the composition and use of variables.
One of the challenges in developing applications in most programming languages is ensuring that the data types you select for your variables are of an appropriate size to hold the information that you want to store in them. Bad things happen when you try to assign a value that is larger than the variable can hold. The most likely outcome in that situation is that the program will abend abnormally when the variable assignment is hit. The worst case is that the program will continue to run, but it will calculate incorrectly.
In VBScript development, there is only one data type, the Variant. The Variant is a special all-purpose data type that acts somewhat like a chameleon, changing its outward appearance based upon how it is used. You can think of a Variant as a magic box that you can place any size object into. No matter what you put into the magic box, it will always appear to be a custom fit. If you place a thimble into it, it will look like a thimble case. If you put a piano into it, it will look like a piano crate.
Variants can contain a wide range of data such as numbers, dates, strings, and references to objects. A Variant will behave as the data type most appropriate to how it is used in any given context. If you assign a number to a Variant variable, the variable will behave as a number. When you assign a string (string being a group of characters like "String of Characters") to a Variant as shown in Listing 7.1, the variable behaves as a string variable, with actions appropriate to string operations. The Variant and its representation is a fluid assignment, changing as operations are performed upon it.
Listing 7.1 i1.htm-Declaring a Variable and Assigning a Value
<SCRIPT LANGUAGE="VBScript"> <!-- Dim aVariable 'we have created a Variant variable aVariable = "5" 'now it looks like a string aVariable = aVariable + 5 'now it looks like an integer with a value of 10 à </SCRIPT>
As you can see from the preceding code, the Variant is a powerful and complex data type. Because of its apparent simplicity, it is easy to assume that it can handle all manner of data, and more specifically, all operations performed upon it successfully. The reality is that when you have variables with different types of data within them interacting (evaluating together within an expression), you can end up with ambiguous or incorrect results if you don't have a firm understanding of the Variant data type and how it works.
A Variant can contain a number of different data types. When a value is placed into a Variant variable, the variable accepts the data and assumes an internal representation of that data which is called a sub-type. You can put whatever you wish into a Variant, and most of the time, it will behave as you expect. Even though the Variant does most of the data-type conversion work for you, it is still important to understand each of the Variant sub-types, the values that they represent, and how they are used.
A Variant with a Boolean sub-type can have only two values, true or false. I can't remember the first time I heard someone say that computers are just a bunch of zeros and ones, but they continue to be correct today. The idea of a variable only having two possible values, 1 or 0, on or off, true or false is exactly what a Boolean sub-type represents (although in many languages the true condition evaluates to -1, I think you get the idea). The Boolean sub-type is extremely useful and is used for flags and settings. In the following example, blnActiveMember has a Boolean Sub-Type:
<SCRIPT LANGUAGE="VBScript"> <!-- if sngDuesPaid >= sngDuesDue then blnActiveMember = true endif à </SCRIPT>
The Byte sub-type can contain a value from 0 to 255. This sub-type is the only safe way to access binary data on a byte-by-byte basis. Higher up in the Visual Basic family tree, you used to be able to operate on binary data using a string data type. With the inclusion in Visual Basic 4 of support for the extended Unicode character set, however, the string data type is no longer one byte per character. A good example of the use of the byte sub-type is when you are reading from or writing to a binary data file.
This sub-type can store integer values in the range of -32,768 to 32,767. It is the sub-type that is used for counters and indexes.
The Long sub-type contains a value in the range of -2,147,483,648 to 2,147,483,647. It has similar uses as the integer sub-type but can host a number of larger magnitudes.
The Single sub-type contains a single-precision floating point number with a value in the range of 1.401298E-45 to 3.402823E38 for positive values and -3.402823E38 to -1.401298E-45 for negative values. If you want to assign a value to a Variant using exponential notation, it takes the form mmmEeee where mmm is the mantissa and eee is the exponent.
This sub-type contains a double-precision floating point number in the range of -1.7976931348232E308 to -4.94065645841247E-324 for negative values and 4.90465645841247E-324 to 1.79769313486232E308 for positive values. To assign a literal to a double, use the form mmmDeee where mmm is the mantissa and eee is the exponent. The D (in place of the E) causes the value to be treated as a double-precision number when converted from a string into a double during an arithmetic operation on the variable.
The currency sub-type is a special type that is used for monetary values. The valid range for currency sub-type values is -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
The date/time sub-type is a most flexible data sub-type, which contains a date in the range of January 1, 100 to December 31, 9999. You can create a Variant of sub-type date in a number of ways. Here are just a few:
dtmCurrentDateTime = Now
will assign the current date and time from your system to the variable dtmCurrentDateTime. Notice the use of the system function Now. The Now function returns the current date and time based upon the system date and time.
DtmTheDate = #02/16/1993#
will assign the date 02-16-1993 to the variable dtmTheDate. If you want to assign a date to a variable using a string, enclose the date within # signs. The Variant date sub-type represents a date and a time. If you were to query the time from the dtmTheDate variable, you would get 12:00 am.
![]()
Whenever you assign a date literal to a variable without specifying a time, the time defaults to 12:00:00 am.
You can also create a date and time assignment for a variable using a string literal.
DtmTheDateTime = #02/16/1996 1:15:00 am#
The preceding line assigns the date and the time to the variable dtmTheDateTime.
The String sub-type contains a variable-length string that can be approximately 2 billion characters in length. It would certainly be a challenge to come up with a string to exhaust that maximum limit. The nice thing about the Variant in general, and the string sub-type in particular, is that it will only use as much memory as you need in any given context. It will not pre-allocate storage for 2 billion characters each time you assign a string to a variable.
This sub-type tells you that the variable has not yet been initialized. If you try to access its value, it will return 0 in a numeric context or an empty string "" in a string context.
The Null sub-type occurs when a variable contains no valid data. This sub-type is only active when you explicitly assign a null to the Variant by an assignment or as the result of an operation on the variable.
This sub-type occurs when you have assigned a variable to hold a reference to an object that you have created.
![]()
See "Managing States and Events with Application and Session Objects," for more information about the object sub-type and creating and using objects in your development, in Chapter 11.
The error sub-type contains a valid error number. You will examine the error sub-type and error handling in general in Chapter 9, "Calling Procedures: Functions and Subroutines."
![]()
The Internal Structure of a Variant Ok. This might fall into that "more that I want to know" category, but, it might be fun to take a quick look at the internal structure of the Variant data type to appreciate the complexity that we never have to deal with in Active Scripting.
The C structure is shown in Listing 7.2, which defines the Variant data type:
Listing 7.2 variant.H-The Header File for the Variant Structure
typedef struct tagVARIANT { VARTYPE vt; unsigned short wReserved1; unsigned short wReserved2; unsigned short wReserved3; union { unsigned char bVal; /* VT_UI1 */ short iVal; /* VT_I2 */ long lVal; /* VT_I4 */ float fltVal; /* VT_R4 */ double dblVal; /* VT_R8 */ VARIANT_BOOL bool; /* VT_BOOL */ SCODE scode; /* VT_ERROR */ CY cyVal; /* VT_CY */ DATE date; /* VT_DATE */ BSTR bstrVal; /* VT_BSTR */ Iunknown FAR* punkVal; /* VT_UNKNOWN */ Idispatch FAR* pdispVal; /* VT_DISPATCH */ SAFEARRAY FAR* parray; /* VT_ARRAY|* */ unsigned char FAR *pbVal; /* VT_BYREF|VT_UI1 */ short FAR* piVal; /* VT_BYREF|VT_I2 */ long FAR* plVal; /* VT_BYREF|VT_I4 */ float FAR* pfltVal; /* VT_BYREF|VT_R4 */ double FAR* pdblVal; /* VT_BYREF|VT_R8 */ VARIANT_BOOL FAR* pbool; /* VT_BYREF|VT_BOOL */ SCODE FAR* pscode; /* VT_BYREF|VT_ERROR */ CY FAR* pcyVal; /* VT_BYREF|VT_CY */ DATE FAR* pdate; /* VT_BYREF|VT_DATE */ BSTR FAR* pbstrVal; /* VT_BYREF|VT_BSTR */ IUnknown FAR* FAR* ppunkVal; /* VT_BYREF|VT_UNKNOWN */ IDispatch FAR* FAR* ppdispVal; /* VT_BYREF|VT_DISPATCH */ SAFEARRAY FAR* FAR* parray; /* VT_ARRAY|* */ VARIANT FAR* pvarVal; /* VT_BYREF|VT_VARIANT */ void FAR* byref; /* Generic ByRef */ }; };The Variant is a structure with a type code and a variety of data members and pointers to the various sub-types of data that it can contain. What makes the Variant so prevalent in our development is that it is the data type for conversations with and between OLE objects. It is used to transmit parameters and return values from the OLE objects that we use in our Active Server Pages development. If you look at the top of the structure, you will see the vt variable of type VARTYPE. This is the variable type code, an enumerated type that contains the sub-type of the variable. When we call the VarType function, it returns the value in the vt variable of the structure, telling us the sub-type of the variable.
The data, depending on its type, is stored in the Variant structure, or within the structure, has a pointer to where the data associated with the variable resides.
The Variant gives us all the data types that we could possibly want without (usually) worrying about what sub-type the Variant actually is. When you do need to find out the sub-type of a variable, you have access to a function called VarType. This function will return the sub-type of the variable that we pass to it. The syntax of the command is
intVarType = VarType(variable_name)
where variable_name is any valid variable. This is especially useful when you are performing any type of arithmetic operations on variables. If you try to add a variable of string sub-type that cannot be resolved to a numeric value with a variable of a numeric sub-type, you will receive a data-type mismatch error. This error is generated because VBScript doesn't know how to add "This is a string" to 5 and come up with a value.
![]()
Notice that in the VarType function, I have called the return value from the VarType function intVarType, telling you to expect an integer return type. Because the only data type that VBScript supports is the Variant, all functions return a Variant data type. The sub-type of the returned Variant from the VarType function, however, is of a sub-type integer.
There are a number of constants that will make the use of the VarType function shown in Listing 7.3 much easier. Instead of having to remember which integer value a particular sub-type correlates to, you can use these constants, outlined in Table 7.1, to check for the sub-type of a variable.
Listing 7.3 i2.htm-Constant Return Values from the VarType Function
<SCRIPT LANGUAGE="VBScript"> <!-- if (vbEmpty = VarType(aVariable)) then else end if --> </SCRIPT>
Table 7.1 VBScript Constants for the VarType Function Return Value
VBScript Constant | Value | Sub-Type | Description |
vbEmpty | 0 | Empty | Uninitialized (default value) |
vbNull | 1 | Null | Contains no valid data |
vbInteger | 2 | Integer | Integer value |
vbLong | 3 | Long | Long integer |
vbSingle | 4 | Single | Single-precision floating-point number |
vbDouble | 5 | Double | Double-precision floating-point number |
vbCurrency | 6 | Currency | Currency |
vbDate | 7 | Date | Date and Time value |
vbString | 8 | String | String |
vbObject | 9 | Object | OLE Automation object |
vbError | 10 | Error | Error number |
vbBoolean | 11 | Boolean | True or False |
vbVariant | 12 | Variant | used only for arrays of Variants |
vbDataObject | 13 | Object | Non-OLE Automation object |
vbByte | 17 | Byte | Byte data |
vbArray | 8192 | Array |
Now, to avoid these messy implicit conversion issues (when you let VBScript decide how best to convert your variables between types), there is an entire host of conversion functions for converting between the numerous sub-types discussed previously.
Because a Variant variable can represent a wide variety of data types, in many cases you will utilize conversion functions to ensure that the format of the variable data is appropriate for its use in a given context. The conversion functions available for your use are outlined in Table 7.2.
Table 7.2 VBScript
Function Name | Converts to Sub-Type | Usage Notes |
CBool | Boolean | Passed-in value must resolve to a numeric. |
CByte | Byte | |
CCur | Currency | |
CDate | Date | Use IsDate() function to ensure that conversion is valid. |
CDbl | Double | |
CInt | Integer | |
CLng | Long | |
CSng | Single | |
CStr | String | Uninitialized values will return "". |
Conversions are handy to have around when you are performing operations that can lead to uncertain results. As an example, consider the case in which you have two variables that you want to add. To ensure that the sub-type of the resulting operation is, for instance, a single, you can convert each variable to type single.
<SCRIPT LANGUAGE="VBScript"> <!-- Dim valOne, valTwo, valResult valOne = 1 valTwo = 2.1 valResult = CSng(valOne) + CSng(valTwo) --> </SCRIPT>
A variable declaration tells the compiler (script processor) that you are reserving space for a variable to use in your application. You can create variables throughout your program within these system enforced guidelines:
The differences between declaring variables within a procedure and within a module will be discussed in the section "Examining the Lifetime of a Variable" found later in this chapter.
You declare a variable in your source code with the Dim statement. This dimensions, or reserves space for the variable for use within the scope of the declaration. You can also implicitly declare a variable in your source code.
A variable that is declared implicitly is not dimensioned before its first use in your code. The script processor automatically creates a variable of the same name as the one that you have used. For example:
<SCRIPT LANGUAGE="VBScript"> <!-- Function leadingZeros(intNumber, intSize) j = intSize - len(aNumber) tempStr = string(j, "0") leadingZeros = tempStr & aNumber End Function --> </SCRIPT>
VBScript will create the variables j and tempStr, and they can be accessed after their initial implicit declaration just as if you had explicitly declared them at the beginning of your function. Although this is a quick and easy way to declare variables, this can lead to numerous problems such as acting on an uninitialized variable or mis-typing a variable in the body of your function, which will run, but will lead to erroneous results. Check out the code that follows.
<SCRIPT LANGUAGE="VBScript"> <!-- Function leadingZeros(intNumber, intSize) j = intSize - len(aNumber) tempStr = String(j, "0") leadingZeros = tmpStr & CStr(intNumber) End Function --> </SCRIPT>
At first glance, the code looks fine. Notice however that on the last line of the function, tempStr was mis-typed as tmpStr. As a result, the function returns the same number that was passed in, without those sought after leading zeros. The tmpStr variable would be created, but would be uninitialized and the leadingZeros function would then return the concatenation of "" and the intNumber passed in, which is, of course, intNumber. Not a great way to start off your coding day!
To avoid the problems discussed previously with implicit variable declarations, be sure to include the Option Explicit command at the beginning of your source code. This will ensure that any variables used in the body of your source code have been explicitly declared using the Dim VarName declaration. Notice that in the following code, the misspelling would generate a run-time error.
<SCRIPT LANGUAGE="VBScript"> <!-- Function leadingZeros(intNumber, intSize) Dim j, tempStr j = intSize - len(aNumber) tempStr = string(j, "0") leadingZeros = tmpStr & CStr(intNumber) End Function --> </SCRIPT>
The length of time that a variable exists, or can be utilized in your code, is defined as the variable's lifetime. The lifetime of a variable is determined by the position in your script that the variable is declared. Variables declared within a function or subroutine will only be visible (able to be operated upon) within that routine. By declaring a variable this way, you create a procedure-level variable with a local scope. When the program returns from the procedure, those procedure-level variables are said to have gone out of scope. Their values have been lost, and they can not be operated on by any other function. Many times it is helpful to have variables that can be used in all of the procedures within your script. When you declare variables outside of a procedure, they are visible to all the procedures in your script. These declarations create script-level variables. Table 7.3 provides a summary of variable scope.
![]()
All local variables will go out of scope (no longer able to access) when their procedure block ends. If you do not use the Option Explicit command, you can mistakenly try to access a local variable beyond its scope and end up creating a new implicitly declared variable of the same name in a different scope.
Table 7.3 The Lifetime of Variables Determined by Their Scope
Declared | Level | Scope | Lifetime |
Within Procedure | procedure-level | local scope | Declaration to end of procedure |
Outside Procedure | script-level | script-level scope | Declaration to end of script |
Once you have decided on the functions that you need to implement in your scripts, it is a fairly easy exercise to determine the scope of the variables that you need to declare. Procedure-level variables are great for temporary use within a function or subroutine for indexes, interim results, and any other case in which you will never need to reference the value of these variables outside of the procedure. Script-level variables are used for those variables that must be available throughout the life of the script. The memory allocated for procedure level variables is released when they go out of scope. Script level variables are not released until the completion of the script. As a general rule, use as few script level variables as possible, although until VBScript allows the use of passing arguments by reference instead of by value, you will be using at least a few script level variables.
![]()
See Chapter 9, "Calling Procedures: Functions and Subroutines," for more information about procedures, passing arguments and ByVal versus ByRef.
![]()
Script-level variables should be declared at the top of your script to ensure that they are visible to all operations and functions within the script.
A variable is only as useful as the information that it contains. To put a value into a variable you assign one to it by using the equal sign. For example:
intConnections = 4
assigns the value 4 to the intConnections variable. The variable is always on the left side of the equal sign. On the right side of the equal sign, you will place a value or an expression, which is just something (a literal, function, variable, calculation, and so on) that evaluates to a value. Here are a few additional assignment examples:
intCurrentState = 10 'intCurrentState has value of 10 intNewState = 20 'IntNewState has value of 20 intOldState = intCurrentState 'intOldState has value of 10 intNewDate = CalcDate(Now) 'dteNewDate has the return value 'from the CalcDate function intCurrentState = intNewState 'intCurrentState has value 20
There is one special kind of assignment that is used when assigning a variable to an object. When you create an object within your script using the assignment operator, you are setting a reference to the object in the variable. You will use the Set keyword to perform this task. The syntax for the Set assignment statement is shown here:
Set objectvar = {objectexpression | Nothing}
The object expression can be the expression used to create the object or a variable which references an existing object. When you assign Nothing to an object variable, the memory associated with the object is released if no other reference to the object is still active. In the following example, the variable objBrowserCap will be set to a reference to the Browser Capabilities object being created.
Set objBrowserCap = Server.CreateObject("MSWC.BrowserType")
To release the memory associated with the object referenced by the objBrowserCap variable, you would set it to nothing.
Set objBrowserCap = Nothing
In Active Server Pages scripting, like most other programming languages, you have the ability to evaluate mathematical expressions by combining numeric data, using operators. There are a number of different types of operators in the environment. Arithmetic, logical, comparison, and concatenation operations can all be performed within your scripts. A list of operators available within VBScript is found in Table 7.4.
Operations within an expression are performed like they are in algebra, following the mathematical principles of precedence. You can override the precedence by containing parts of the expression within parentheses. When you have an expression with multiple operator types, the operators are evaluated based upon the following hierarchy: arithmetic operators are evaluated first; comparison operators are evaluated next; and logical operators are evaluated last. Within any given expression group (within parentheses), operators of the same type are performed from left to right.
Table 7.4 Scripting Operators
Operator Type | Symbol | Description | Example |
Arithmetic | * | Multiplication | 2 * 2 = 4 |
/ | Division | 4 / 2 = 2 | |
\ | Integer Division | 5 \ 2 = 2 | |
+ | Addition | 2 + 2 = 4 | |
- | Subtraction | 4 - 2 = 2 | |
Mod | Modulus (remainder) | 5 Mod 2 = 1 | |
^ | Exponential | 2 ^ 3 = 8 | |
Comparison | = | Equal to | 4 = 4 is true |
<> | Not equal to | 4 <> 4 is false | |
< | Less than | 4 < 3 is false | |
> | Greater than | 4 > 3 is true | |
<= | Less than or equal to | 4 <= 3 is false | |
>= | Greater than or equal to | 4 >= 3 is true | |
Is | Object Comparison | objOne Is objTwo | |
Logical | And | Conjunction | If a and b are true, then true |
Not | Negation | If not a and a is false, then true | |
Or | Disjunction | If a or b is true, then true | |
Eqv | Equivalence | If a and b are both true or both false, then true | |
Imp | Implication | If a true and b false, false, else true or Null | |
Xor | Exclusion | If a true and b false or b true and a false, true | |
Concatenation | & | Concatenates values | "Mr. " & "Smith" = "Mr. Smith" |
In Table 7.4, there are two special operators that you should take note of. The first is the concatenation operator, &. This operator is used to concatenate two strings.
<SCRIPT LANGUAGE="VBScript"> <!-- strCaption = "My Name Is: " strName = "Donny Brook" strOutput = strCaption & strName --> </SCRIPT>
The resulting strOutput variable contains the string My Name Is: Donny Brook.
![]()
You can use the + operator to concatenate string variables as well, and this works fine when both are of sub-type string. If both sub-types are numeric, the values will be added. When one of the sub-types is numeric and the other is a string, the string will be evaluated to a numeric type (implicit conversion) and then added to the other numeric variable. If the string cannot be converted to a numeric value, a run-time error will occur. For safe concatenation, always use the & operator.
The second special operator is the Is operator. This operator will determine whether two object variables point to the same object, as in:
blnResult = objOne Is objTwo
If the two object variables point to the same object, blnResult will be true, otherwise it will be false. The Is operator will become extremely useful as we get into the Active Server Pages objects and components discussions in Part III.
What's in a name? Well, that depends. Application development will always be equal parts of art and science, and the process of selecting names for variables is no different. The names that you assign to variables do not affect the performance of the application in any way, but incorrect use of variable naming can lead to numerous problems. For example, I know several C developers who take pride in the terseness of their code. The more functions they can put on a line and the more inconsistent their use of naming rules, the better. Naming variables a, b, or c works extremely well in Euclidean geometry, but in your application source code, variable naming patterns can be directly correlated to the maintainability and readability of your code. I shudder to think of the countless hours I've spent working my way through poorly named and documented code, trying to understand what the variables represent and how they are used in the program.
![]()
When in doubt, use the most descriptive name possible for your variables. The next person to maintain your code will thank you for it. Use LoanNumber instead of lnbr, try CustomerAccount instead of actno. When you have only two or three variables in any scope, you have less reason to be so prolific, but as your scripts increase in size and complexity, these little hints that your variable names provide will be of immeasurable value.
There are naming rules that limit you to a certain extent as you begin to create names for the variables in your application. These rules for variable naming in VBScript include:
All variable names:
Now that the system-enforced rules are out of the way, you can move on to the variable naming conventions. Naming conventions are guidelines that are enforced only by the developer, but when used consistently across your source code, they will ensure that the programmers that follow you will have extra hints concerning the use of variables in your program. In C language Windows development, the naming convention that is most often used is called Hungarian notation. This is a C language naming convention credited to the Microsoft programmer Charles Simonyi, in which you can determine a variable's type simply by looking at its prefix. The same idea has been implemented for the naming conventions used in VBScript development. In the brief code snippets listed previously in the chapter, you might have noticed some strange looking prefixes ahead of the variable names. These VBScript prefixes, found in Table 7.5, give you hints as to what sub-type to expect within the Variant variable.
Table 7.5 VBScript Preferred Variable Naming Conventions
Sub-Type | Variable Pre-Fix | An Example |
Boolean | bln | blnActiveAccount |
Byte | byt | bytImageData |
Date/Time | dtm | dtmClientBirthday |
Double | dbl | dblMaxDelay |
Error | err | errAccountCreation |
Integer | int | intPassCounter |
Long | lng | lngRateOfTravel |
Object | obj | objDatabase |
Single | sng | sngAvgSpeed |
String | str | strLastName |
The use of naming conventions in your development is entirely voluntary and is in no way enforced by the compiler or script processor. There is no system or server constraint that will require you to follow any particular naming convention. Professional developers utilize naming conventions in code because it enhances the quality and maintainability of their systems.
Your company has likely already implemented standard naming conventions for in-house development. If there are none, it is prudent to follow the vendor's naming conventions as that is most often what will be implemented in other development shops.
As you read at the beginning of the chapter, data is broken down into variables and constants. VBScript provides the Const declaration to insure that a constant variable is not assigned a value during script execution. To define a variable as a constant, you use the Const keyword, along with an assignment when declaring the variable. Also, when declaring constants, use all upper case letters, separating words with underscores. This is another standard naming convention as shown in the following constant declaration:
Const MAX_ITERATIONS = 10
Now when you use the constants in your code, there is no mistaking their intent or their use. This will also help to ensure that Joe Programmer, who now maintains your code, will not mistakenly try to change one of your constant variables. If Joe does attempt to assign a value to a Const variable within the script, an illegal assignment run-time error will be generated..
The last piece of the naming convention puzzle concerns the variable name's hint as to the scope in which it exists. For procedure-level variables, no prefix is recommended. For those variables that are script-level, add an s to the beginning of the variable name.
Dim sblnAccountActiveFlag 'Active Accounts have this flag set to true
Now, just by seeing the variable name, we know that this is a script-level variable that holds a variable of sub-type Boolean, and from the variable name, that the variable is a flag that shows the status of an account.
We have been talking a lot about naming conventions, variable prefixes, and the use of descriptive names for variables to give you and other developers hints as to what you are trying to accomplish in your application. To take this to the next level, you will want to add comments to your code along the way as well. When you have to pick up code that you wrote 5 or 6 months ago to add functionality or (not that this will happen to you) to fix a bug, you will thank yourself for commenting your code. As Steve McConnel notes in Code Complete, commenting code correctly can enhance its readability and maintainability, but comments implemented poorly can actually hurt one's understanding of the code.
There are a few main rules that you can use as a guide for commenting your code.
A good template for commenting functions and subroutines follows.
'******************************************************* ' Description: A brief description of the purpose of ' the procedure ' Arguments : A listing of each argument and what it ' is used for ' Returns : what, if anything, does the proc return ' Modified : The date the procedure was last modified, ' the developer who did it, and what was ' changed. '********************************************************
Comments within the code itself should be placed to enhance the understanding of the code. As you add blocks of functionality, you should add comments that help to explain the flow. For example:
<SCRIPT LANGUAGE="VBScript"> <!-- Dim objDBConnection, objRSCustomerList Dim strQuery 'Create the database object and open the database Set objDBConnection = Server.CreateObject("ADO.Connection") objDBConnection .Open "UserDatabase" 'Select Customers that reside in CA strQuery = "Select Name, Address from Customer where State= 'CA' set objCustomerList = objDBConnection.Execute(strQuery) --> </SCRIPT>
Each major functional step should have an associated comment. As you nest and indent the code within loops, the comments should also be indented. A good rule of thumb for indenting code is to use 3 spaces for each logical nesting.
<SCRIPT LANGUAGE="VBScript"> <!-- if (blnActiveLoan) then 'Update customer Information else 'Send negative acknowledgment end if --> </SCRIPT>
Many times you will find yourself dealing with a number of related items that you want to perform the same or similar actions upon. Using unique variable names for these related items is quite easy when you are only dealing with three or four distinct data items. When you want to relate tens or hundreds of items together and perform operations on them, however, you need a special type of variable construct: the array. With an array, you can access a group of related data items by using the same name, and any particular data member by using a unique index. This makes processing the items within the array very efficient, as you can loop through the array data using an index value.
All elements of an array in VBScript have the same data type, the Variant. The added benefit of having Variant arrays is that you can have multiple sub-types across members of the array. You can declare two types of arrays, fixed-length and dynamic.
A fixed-length array is an array in which the number of members will not change over the lifetime of the array variable. To create a fixed-length array, you specify the number of elements that you wish to have in the declaration of the array variable. For example, the declaration:
Dim dblCharges(10)
creates an array of 11 items with index numbers from 0 to 10.
![]()
All VBScript arrays use zero-based indexes. Currently, VBScript does not permit you to change the base of indexes as you can in Visual Basic and Access. Also, it does not recognize explicit lower bounds; e.g.,
To assign a value to a member of the array, you include the subscript on the left side of the assignment operator:
dblCharges(0) = 100.50 dblCharges(1) = 125.25
Assume that in the previous examples you have assigned each of the array elements a value. Determining the total of all the values in the array is simply a process of looping through the index and adding the values together as follows:
<SCRIPT LANGUAGE="VBScript"> <!-- Dim i, dblTotalCharges For i = 0 to 10 dblTotalCharges = dblTotalCharges + dblCharges(i) Next --> </SCRIPT>
You can also create arrays with more than one dimension. In a two-dimensional array, you can think of the first array index as the row in a spreadsheet and the second as the column. To declare a two-dimensional array, just include a second index value on the declaration statement.
Dim intMultiArray(9,9)
This will create a two dimensional array of 10 by 10 elements. You access the members of the multi-dimensional array just as you would a single-dimensional array.
Dim intMultiArray(1 to 9, 1 to 9) intMultiArray(4,5) = 15
You can also easily loop through all of the elements in a multi-dimensional array just as we did for the single-dimension array. Using the previously declared array, the loop looks like:
<SCRIPT LANGUAGE="VBScript"> <!-- Dim j, k, intTotal for j = 0 to 9 for k = 0 to 9 intTotal = intTotal + intMultiArray(j, k) next k next j --> </SCRIPT>
There are many situations in which you will not know how many array items you will ultimately require for a given process. You could declare a huge array and hope that you will not exceed its upper bound. This will surely work in most cases, but it is horribly inefficient, as well as quite inelegant. A better option would be to create a dynamic array.
A dynamic array can be resized over its lifetime. You can create single and multi-dimensional dynamic arrays. To create a dynamic array, you omit the index number from the array declaration.
Dim dynArray()
You can also use the ReDim statement to declare a procedurelevel dynamic array.
ReDim dynArray(25)
This will create a dynamic array variable with 26 initial elements.
To change the size of a declared dynamic array variable, you use the ReDim statement again, this time including the index for the number of items you want in the array. To increase the size of the array, you call the ReDim function again and again. If you want to keep the current contents of the array intact when you change the size of the array, use the keyword Preserve on the ReDim statement.
Dim dynArray() 'the dynamic array is declared ReDim dynArray(15) 'set the array size to 16 ReDim Preserve dynArray(20) 'reset the size to 21, preserving the contents
![]()
If you ReDim Preserve an array to a smaller size than it currently is, you will lose the data beyond the new index size.
Also, if you ReDim a multidimensional array, you can only change the last dimension; otherwise, you will generate a run-time error.
And finally, the ReDim statement is only allowed within a procedure. It will generate a run-time error if used at any other level.
You now know what a variable is, how to declare one, and how to use the operators provided by VBScript to create expressions. You also should have a good idea of how to create meaningful, descriptive variable names as well as how to document your scripts. In the next few chapters, you round out your base skills to gain the tools to begin creating Active Server scripts right away.
In the coming chapters, you will leverage your understanding of variable typing, naming, and scoping with:
© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.