| VB Script Basics |
| Data Types |
What are the VBScript Data Types?
|
Subtype Description Empty Variant is uninitialized. Value is either 0 for numeric variables or a zero-length string ("") for string variables. Null Variant intentionally contains no valid data. Boolean Contains either True or False. Byte Contains integer in the range 0 to 255. Integer Contains integer in the range -32,768 to 32,767. Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807. Long Contains integer in the range -2,147,483,648 to 2,147,483,647. Single Contains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values. Double Contains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. Date (Time) Contains a number that represents a date between January 1, 100 to December 31, 9999. String Contains a variable-length string that can be up to approximately 2 billion characters in length. Object Contains an object. Error Contains an error number. If you want to convert from one subtype to another, there is a rich set of conversion functions you can use. In addition, the VarType function returns information about how your data is stored within a Variant.
| Variables |
What Is a Variable?
A variable is a convenient placeholder that refers to a computer memory location where you can store program information that may change during the time your script is running. For example, you might create a variable called ClickCount to store the number of times a user clicked an object on a particular Web page. Where the variable is located in computer memory is unimportant. What's important is that you only have to refer to it by name to see its value or to change its value. In VBScript, variables are always of one fundamental data type, Variant.
Declaring Variables
You declare variables explicitly in your script using the Dim statement, the Public statement, and the Private statement. For example:
Dim DegreesFahrenheit
You declare multiple variables by separating each variable name with a comma. For example:
Dim Top, Bottom, Left, Right
You can also declare a variable implicitly by simply using its name somewhere in your script. That's not generally considered to be a good practice because you could misspell the variable name in one or more places, causing unexpected results when your script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables. The Option Explicit statement should be the first statement in your script.
Naming Restrictions
Variable names follow the standard rules for naming anything in VBScript. A variable name:Must begin with an alphabetic character.
Cannot contain an embedded period.
Must not exceed 255 characters.
Must be unique in the scope in which it is declared.
Scope and Lifetime of Variables
When you declare a variable within a procedure, only code within that procedure can access or change the value of that variable; it has local scope and is known as a procedure-level variable. Sometimes, however, you need to use a variable with a broader scope, such as one whose value is available to all the procedures within the same script. If you declare a variable outside a procedure, you make it recognizable to all the procedures in your script. This kind of script-level variable is said to have script-level scope.The length of time a variable exists is its lifetime. A script-level variable's lifetime extends from the time it is declared until the time the script is finished running. A local variable's lifetime begins when its declaration statement is encountered as the procedure begins, and ends when the procedure concludes. Local variables are ideal as temporary storage space when a procedure is executing. You can have local variables of the same name in several different procedures because each is recognized only by the procedure in which it is declared.
A variable's scope is determined by where you declare it. At script level, the lifetime of a variable is always the same. It exists for as long as the script is running. At procedure level, a variable exists only so long as you are in the procedure. When the procedure exits, the variable is destroyed.
Assigning Values to Variables
Values are assigned to variables creating an expression as follows: the variable is on the left side of the expression and the value you want to assign to the variable is on the right. For example:B = 200Scalars and Arrays
Much of the time, you just want to assign a single value to a variable you've declared. A variable containing a single value is a scalar variable. Other times, it's convenient to assign more than one related value to a single variable. Then you can create a variable that can contain a series of values. This is called an array variable. Array variables are declared much the same way as scalar variables. The difference is that a declaration of an array variable uses parentheses following the variable name. In the following example, a single-dimension array containing 11 elements is declared:Although the number shown in the parentheses is 10, all arrays in VBScript are zero-based, so this array actually contains 11 elements. In a zero-based array, the number of array elements is always the number shown in parentheses plus one. This kind of an array is called a fixed-size array.Dim A(10)You assign data to each of the elements of the array using an index into the array. Beginning at zero and ending at 10, data can be assigned to the elements of an array as follows:
Similarly, the data can be retrieved from any element using an index into the particular array element you want. For example:A(0) = 256 A(1) = 324 A(2) = 100 . . . A(10) = 55Arrays aren't limited to a single dimension. You can have as many of 60 dimensions although most people can't comprehend more than about three or four. Multiple dimensions are declared by separating an array's size numbers in the parentheses with commas. In the following example, the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns:SomeVariable = A(8)In a two-dimensional array, the first number is always the number of rows; the second the number of columns.Dim MyTable(5, 10)
You can also declare an array whose size changes during the time your script is running. This is called a dynamic array. The array is initially declared within a procedure using either the Dim statement as with any other array, or using the ReDim statement. The difference is that no size or number of dimensions is placed inside the parentheses. For example:
To use a dynamic array, you must subsequently use ReDim to determine the number of dimensions and the size of each. In the following example, ReDim sets the initial size of the dynamic array to 25. A subsequent ReDim statement resizes the array to 30, but uses the Preserve keyword to preserve the contents of the array as the resizing takes place.Dim MyArray() ReDim AnotherArray()There is no limit to the number of times you can resize a dynamic array, but you should know that if you make an array smaller than it was, you lose the data in the eliminated elements.ReDim MyArray(25) . . . ReDim Preserve MyArray(30)
| Simple VB Script Page |
A Simple Page
With Microsoft Internet Explorer 3.0, you can view the page produced by the HTML code below. If you click the button on the page, you see VBScript in action.
The result is a little underwhelming: you see a dialog box with a phrase in it (Latin for "Wonderful to behold"). However, there's quite a bit going on.<HTML> <HEAD><TITLE>A Simple First Page</TITLE> <SCRIPT LANGUAGE="VBScript"> <!-- Sub Button1_OnClick MsgBox "Mirabile visu." End Sub --> </SCRIPT> </HEAD> <BODY> <H3>A Simple First Page</H3><HR> <FORM><INPUT NAME="Button1" TYPE="BUTTON" VALUE="Click Here"></FORM> </BODY> </HTML>When Internet Explorer reads the page, it finds the <SCRIPT> tags, recognizes there is a piece of VBScript code, and saves the code. When you click the button, Internet Explorer makes the connection between the button and the code, and runs the procedure.
The Sub procedure in the <SCRIPT> tags is known as an event procedure. You'll notice that there are two parts to the procedure name: the name of the button, Button1 (from the NAME attribute in the <INPUT> tag), and an event name, OnClick; the two names are joined by an underscore. Any time the button is clicked, Internet Explorer looks for and runs the corresponding event procedure, Button1_OnClick.
Internet Explorer 3.0 defines the events available for form controls in the Scripting Object Model documentation.
Pages can use combinations of controls and procedures, too. The next page, VBScript and Forms, shows some simple interactions between controls.
Other Ways to Attach Code to Events
You can attach VBScript code to events in two other ways, although the preceding way is probably the simplest and most general.Internet Explorer 3.0 allows you to add short sections of inline code in the tag defining the control. For example, the following <INPUT> tag performs precisely the same action as the previous code example when you click the button:
Notice that the function call itself is enclosed in single quotation marks, and the string for the MsgBox function is enclosed in double quotation marks. You can use multiple statements as long as you separate the statements with colons (:).<INPUT NAME="Button1" TYPE="BUTTON" VALUE="Click Here" OnClick='MsgBox "Mirabile visu."'>You can also write a <SCRIPT> tag so that it applies only to a particular event for a specific control:
Because the <SCRIPT> tag already specifies the event and the control, you don't use the Sub and End Sub statements.<SCRIPT LANGUAGE="VBScript" EVENT="OnClick" FOR="Button1"> <!-- MsgBox "Mirabile visu." --> </SCRIPT>
VB Script & Forms Simple Validation
You can use Visual Basic Scripting Edition to do much of the form processing that you'd usually have to do on a server. You can also do things that just can't be done on the server.Here's an example of simple client-side validation. The HTML code is for a text box and a button. If you use Microsoft Internet Explorer version 3.0 to view the page produced by the code, you'll see a small text box with a button next to it.
The only difference between this text box and the examples on A Simple VBScript Page is that the Value property of the text box is used to check the entered value. To get the Value property, the code has to qualify the reference to the name of the text box.<HTML> <HEAD><TITLE>Simple Validation</TITLE> <SCRIPT LANGUAGE="VBScript"> <!-- Sub Submit_OnClick Dim TheForm Set TheForm = Document.ValidForm If IsNumeric(TheForm.Text1.Value) Then If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then MsgBox "Please enter a number between 1 and 10." Else MsgBox "Thank you." End If Else MsgBox "Please enter a numeric value." End If End Sub --> </SCRIPT> </HEAD> <BODY> <H3>Simple Validation</H3><HR> <FORM NAME="ValidForm"> Enter a value between 1 and 10: <INPUT NAME="Text1" TYPE="TEXT" SIZE="2"> <INPUT NAME="Submit" TYPE="BUTTON" VALUE="Submit"> </FORM> </BODY> </HTML>You can always write out the full reference Document.ValidForm.Text1. However, where you have multiple references to form controls, you'll want to do what was done here. First declare a variable. Then use the Set statement to assign the form to the variable TheForm. A regular assignment statement doesn't work here; you must use Set to preserve the reference to an object.
Using Numeric Values
Notice that the example directly tests the value against a number: it uses the IsNumeric function to make sure the string in the text box is a number. Although VBScript automatically converts strings and numbers, it's always a good practice to test a user-entered value for its data subtype and to use conversion functions as necessary. In addition, when doing summation with text box values, convert the values explicitly to numbers since the plus sign (+ operator) represents both addition and string concatenation. For example, if Text1 contains "1" and Text2 contains "2", you see the following results:A = Text1.Value + Text2.Value ' A is "12" A = CDbl(Text1.Value) + Text2.Value ' A is 3Validating and Passing Data Back to the Server
The simple validation example uses a plain button control. If it used a Submit control, the example would never see the data to check iteverything would go immediately to the server. Avoiding the Submit control lets you check the data, but it doesn't submit it to the server. That requires an additional line of code:To send the data to the server, the code invokes the Submit method on the form object when the data is correct. From there, the server handles the data just as it otherwise wouldexcept that the data is correct before it gets there. You'll find complete information about the Submit method and other methods on the Internet Explorer Scripting Object Model page.<SCRIPT LANGUAGE="VBScript"> <!-- Sub Submit_OnClick Dim TheForm Set TheForm = Document.ValidForm If IsNumeric(TheForm.Text1.Value) Then If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then MsgBox "Please enter a number between 1 and 10." Else MsgBox "Thank you." TheForm.Submit ' Data correct; send to server. End If Else MsgBox "Please enter a numeric value." End If End Sub --> </SCRIPT>So far, you've seen only the standard HTML <FORM> objects. Internet Explorer 3.0 also lets you exploit the full power of ActiveX controls (formerly called OLE controls) and Java objects.
| VBScript Coding Conventions |
What Are Coding Conventions?
Coding conventions are suggestions that may help you write code using Microsoft Visual Basic Scripting Edition. Coding conventions can include the following:The main reason for using a consistent set of coding conventions is to standardize the structure and coding style of a script or set of scripts so that you and others can easily read and understand the code.
- Naming conventions for objects, variables, and procedures
- Commenting conventions
- Text formatting and indenting guidelines
Using good coding conventions results in precise, readable, and unambiguous source code that is consistent with other language conventions and as intuitive as possible.
Constant Naming Conventions
Constant names should be uppercase with underscores (_) between words. For example:USER_LIST_MAX NEW_LINEVariable Naming Conventions
For purposes of readability and consistency, use the prefixes listed in the following table, along with descriptive names for variables in your VBScript code.
Subtype Prefix Example Boolean bln blnFound Byte byt bytRasterData Date (Time) dtm dtmStart Double dbl dblTolerance Error err errOrderNum Integer int intQuantity Long lng lngDistance Object obj objCurrent Single sng sngAverage String str strFirstName Variable Scope
Variables should always be defined with the smallest scope possible. VBScript variables can have the following scope.
Scope Where Variable Is Declared Visibility Procedure-level Event, Function, or Sub procedure Visible in the procedure in which it is declared. Script-level HEAD section of an HTML page, outside any procedure Visible in every procedure in the script. Variable Scope Prefixes
As script size grows, so does the value of being able to quickly differentiate the scope of variables. A one-letter scope prefix preceding the type prefix provides this, without unduly increasing the size of variable names.
Scope Prefix Example Procedure-level None dblVelocity Script-level s sblnCalcInProgress Descriptive Variable and Procedure Names
The body of a variable or procedure name should use mixed case and should be as complete as necessary to describe its purpose. In addition, procedure names should begin with a verb, such as InitNameArray or CloseDialog.For frequently used or long terms, standard abbreviations are recommended to help keep name length reasonable. In general, variable names greater than 32 characters can be difficult to read.
When using abbreviations, make sure they are consistent throughout the entire script. For example, randomly switching between Cnt and Count within a script or set of scripts may lead to confusion.
Object Naming Conventions
The following table lists recommended conventions for the various objects you may encounter while programming VBScript.
Object type Prefix Example 3D Panel pnl pnlGroup Animated button ani aniMailBox Check box chk chkReadOnly Combo box, drop-down list box cbo cboEnglish Command button cmd cmdExit Common dialog dlg dlgFileOpen Frame fra fraLanguage Horizontal scroll bar hsb hsbVolume Image img imgIcon Label lbl lblHelpMessage Line lin linVertical List Box lst lstPolicyCodes Spin spn spnPages Text box txt txtLastName Vertical scroll bar vsb vsbRate Slider sld sldScale Code Commenting Conventions
All procedures should begin with a brief comment describing what they do. This description should not describe the implementation details (how it does it) because these often change over time, resulting in unnecessary comment maintenance work, or worse yet, erroneous comments. The code itself and any necessary inline comments describe the implementation.Arguments passed to a procedure should be described when their purpose is not obvious and when the procedure expects the arguments to be in a specific range. Function return values and other variables that are changed by the procedure, especially through reference arguments, should also be described at the beginning of each procedure.
Procedure header comments should include the following section headings. For examples, see the section "Formatting Your Code" that follows.
Remember the following points:
Section Heading Comment Contents Purpose What the procedure does (not how). Assumptions List of any external variable, control, or other element whose state affects this procedure. Effects List of the procedure's effect on each external variable, control, or other element. Inputs Explanation of each argument that isn't obvious. Each argument should be on a separate line with inline comments. Return Values Explanation of the value returned.
- Every important variable declaration should include an inline comment describing the use of the variable being declared.
- Variables, controls, and procedures should be named clearly enough that inline comments are only needed for complex implementation details.
- At the beginning of your script, you should include an overview that describes the script, enumerating objects, procedures, algorithms, dialog boxes, and other system dependencies. Sometimes a piece of pseudocode describing the algorithm can be helpful.
Formatting Your Code
Screen space should be conserved as much as possible, while still allowing code formatting to reflect logic structure and nesting. Here are a few pointers:
- Standard nested blocks should be indented four spaces.
- The overview comments of a procedure should be indented one space.
- The highest level statements that follow the overview comments should be indented four spaces, with each nested block indented an additional four spaces. For example:
'********************************************************* ' Purpose: Locates the first occurrence of a specified user ' in the UserList array. ' Inputs: strUserList(): the list of users to be searched. ' strTargetUser: the name of the user to search for. ' Returns: The index of the first occurrence of the strTargetUser ' in the strUserList array. ' If the target user is not found, return -1. '********************************************************* Function intFindUser (strUserList(), strTargetUser) Dim i ' Loop counter. Dim blnFound ' Target found flag intFindUser = -1 i = 0 ' Initialize loop counter Do While i <= Ubound(strUserList) and Not blnFound If strUserList(i) = strTargetUser Then blnFound = True ' Set flag to True intFindUser = i ' Set return value to loop count End If i = i + 1 ' Increment loop counter Loop End Function