If you are familiar with Visual Basic in any of its versions, you will be right at home with VBScript. VBScript has all of the usual features and issues of a programming language.
VBScript Data TypesVBScript has only one data type which is called Variant. Variant, as its name implies, can contain various types of data. The type of data that is stored in a variable is recorded in the variable as a subtype. If you have the number 100 stored in a variable of the Variant data type, when your code context treats it as a string, it behaves as a string. When you use it in a calculation it will behave as a number. VBScript will convert the data as necessary depending on the context.
The subtypes of the Variant data type are:
Empty. - Variant is uninitialized. If the context uses it as a number, the value is zero. If the context uses it as a string it is a zero-length string ("").
Null. - Variant contains no valid data. Nulls can be confusing. It does not mean blank. A null in a logical compare will not match any value.
Boolean. - The value is true or false.
Byte. - The value is an integer in the range of 0 to 255. This is not a signed value.
Integer. - The value is a signed integer in the range of -32,768 to 32,767. Note that there is no unsigned integer.
Long. - The value is a long integer in the range of -2,147,483,648 to 2,147,483,647.
Currency. - -922,337,203,685,477.5808 to 922,337,203,685,477.5807 is the range of values.
Single. - The values are a single-precision, floating point numbers in the range of -3.402823E38 to -1.401298E-45 for negative values to 1.401298E-45 to 3.402823E38 for positive values.
Double. - The values are a double-precision, floating point number in the range of -1.79769313486232E308 to -4.94065645841247E-324 for negative values to 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Date (Time). - The value is a number that represents a date and time between January 1, 100 to December 31, 9999.
String. - Contains a variable length string that can be roughly 2 billion characters in length.
Object. - Contains an object.
Error. - Contains an error number.
The self-converting Variant type does not always work as expected. You will still encounter the occasional type mismatch error condition. There are some VBScript functions that allow you to examine the Variant subtype and to convert the subtype to eliminate the type mismatch problem. One of the consequences of the variant data type is that when a variable is declared, the type is not specified.
VBScript FunctionsVBScript contains the functions that you are familiar with from Visual Basic. The full list of functions will not be covered here. There are some functions specifically for working with the Variant data type subtypes that deserve some mention. The first of these are two that are used to determine the subtype of a variable.
VarType(varname) returns a numeric value depending on the Variant subtype, for example 2 is an integer and 8 is a string.
TypeName(varname) returns a string that tells the Variant subtype, for example "byte" or "string".
There are several functions that test for specific Variant subtypes. Two examples include the following:
IsArray(varname) returns a true or false value depending on whether the variable is an array.
IsNull(varname) returns a true or false value depending on whether the variable value is null or not.
There are functions that will convert the Variant subtype, which will provide you with a fixed known subtype. Two examples are:
CInt(experssion) returns a value of the integer subtype.
CStr(expression) returns a value in the form of a string subtype.
The Visual Basic functions that you will not find in VBScript are Val() and Str(). You will need to use the CStr() or other Variant subtype conversion functions to accomplish the same result.
VBScript VariablesDeclaring a variable in VBScript is very similar to Visual Basic. In Visual Basic, if you don't declare the type, the variable is a variant. In VBScript, you can't declare the type because all variables are of the type Variant. An example of a variable declaration is:
Dim MyVarMultiple variables can be declared and separated by commas as in:
Dim MyVar, YourVar, OurVarGive a variable an initial value:
MyVar = 10The variable has also established the subtype of integer with the value of this assignment.
Variable naming restrictions are that the name must begin with an alphabetic character, cannot contain an embedded period, must not be longer than 255 characters, and must be unique within the scope of the variable.
Arrays may be created as:
Dim MyArray (10)Multiple dimension arrays may be created as:
Dim MyArray (5, 10)Arrays can be resized with the ReDim statement. If the values in the array are to be preserved during the resize the statement is as follows:
ReDim Preserve MyArray (30)Variables in VBScript can have a scope and visibility of a single precedure or can have a script-wide scope and visibility. If the variable is declared in a procedure, its scope and visibility is limited to the procedure. If it is declared outside of a procedure, usually in the <HEAD> section of the HTML page, it will have script-wide scope and visibility.
VBScript ConstantsA constant is data value that has a name. The value is substituted for the constant in a VBScript statement. The value of the constant never changes. An example of a constant is PI. PI has a value of 3.1416 and on and on. If you are writing a program that uses the value of PI in calculations, after you have declared the constant PI, you can use PI rather than typing out the number. This allows you to determine at the beginning that you will use PI with 4 decimal places uniformly throughout the program.
To declare a constant, the key word CONST is used. An example is:
CONST PIAfter you declare the constant you need to initialize its value. For example:
PI = 3.1416When you are declaring a string constant, the value is enclosed in quotation marks as:
Const MY_STRING MY_STRING = "This is my string."For date constants, the value is enclosed in the pound sign (#).
Const MY_BIRTHDATE MY_BIRTHDATE = #5/15/1955# Control of Program Flow in VBScriptThere are two basic types of program flow control statements. These are conditional statements such as the If...Then...Else type of logic and the repetitive execution of code or Loops.
There is one type of program flow control statement that is present in Visual Basic that does not exist in VBScript. This is the GOTO statement. Whether the omission is intentional or an oversight is unknown. The primary issue that the lack of a GOTO statement presents to the programmer is the requirement to perform all error handling in line.
The conditional statements include the single line If...Then syntax:
If A = B Then Myfunctionand the multiple-line or block If...Then syntax as in:
If A = B Then Myfunction Else Anotherfunction End IfIf statements can be nested just as in Visual Basic and the ElseIF usage is valid in VBScript.
The Select Case statement is also supported as in:
Select Case MyVariable Case Value1 Function1 Case Value2 Function2 Case Else FunctionElse End Select
For repetitive processing, VBScript supports Do...Loop logic identical to the forms supported in Visual Basic. The Exit Do function is supported and the Do Until and Do While forms work. For example:
Sub MyDoLoopExample() Dim mycounter, someNumber mycounter = 0 someNumber = 0 Do Until someNumber = 100 someNumber = someNumber + 1 mycounter = mycounter + 1 If someNumber > 10 Then Exit Do Loop MsgBox "The loop made " & counter & " repetitions." End Sub
This loop should make eleven repetitions.
VBScript also supports the While...Wend and the For...Next statements.
VBScript OperatorsVBScript has the full range of Visual Basic operators, including logical operators, comparison operators, concatenation operators, and arithmetic operators. When several operators are used in succession the Visual Basic rules of Operator Precedence are followed. The arithmetic operators are:
+ - Addition - X = A + B
- - Subtraction - X = A - B
* - Multiplication - X = A * B
/ - Division - X = A/B
\ - Integer Division - X = A\B (X will be an integer)
^ - Exponentation - X = A^B
Mod - Modulus Arithmetic - X = A Mod B
The comparison operators are used to compare values or objects. The result returned is True or False. The comparison is often used to determine as If A = B Then.... The comparison operators available in VBScript are:
= - Equality - A = B
> - Greater than - A > B
< - Less than - A < B
<> - Not equal to - A <> B
>= - Greater than or equal to - A >= B
<= - Less than or equal to - A <= B
Is - Tests to see if two objects are the same object. ObjectA Is ObjectB
Logical operators return a value of True or False. As an example, in a test that is selecting rows from a table based on testing the values found in column A and column B, you could use the logical statement "Select the row if Column A = 10 And Column B = 25". Using the And operator, both conditions must be true. A full explanation of the logical operators is beyond the purpose of this chapter. For a complete explanation, the VB 5.0 help files are excellent. The logical operators provided by VBScript are:
And - Logical conjunction
Not - Logical negation
Or - Logical disjunction
Xor - Logical exclusion
Eqv - Logical equivalence
Imp - Logical implication
There is one concatenation operator in VBScript, &. It is used to put two strings together. As an example, if you want to create a new string value that is made up of two other strings the statement would be:
StringVarNew = StringVar1 & StringVar2
If StringVar1 contained "ABC" and StringVar2 contained "DEF", then StringVarNew would contain "ABCDEF".
VBScript ProceduresVBScript uses two types of procedures, Sub and Function. The basic difference is that a function can return a value and a sub can't.
Both a Sub and a Function can take arguments. When you create a Sub, you use the form shown in Listing 13.4 below. It calculates your weight in kilograms based on your input in pounds.
Listing 13.4 - VBScript Sub Code Snippet - The VBScript to create a Sub procedure.
Sub WeightConversion() WeightLbs = InputBox("Please enter your weight in pounds.", 1) WeightKg = WeightLbs / 2.2 MsgBox "Your weight in Kilograms is " & WeightKg End Sub
If you wanted to create a Function that would perform the weight conversion it would look like Listing 13.5,
Listing 13.5 - VBScript Function Code Snippet - The Function receives the weight in pounds and returns the weight in kilograms.
Function ConvertWeight(WeightLbs) ConvertedWeight = WeightLbs / 2.2 End Function
When this function is used the code is:
WeightKg = ConvertWeight(WeightLbs)
The Sub or Function can be placed anywhere in the HTML document. A suggested location is in the <HEAD> section of the document. When it is located here it does not affect the appearence of the document and does not have to be placed in comment tags to keep it from printing on a browser that is not VBScript capable.