Microsoft® Visual Basic® Scripting Edition
Microsoft® Visual Basic® Scripting Edition
com
Microsoft Visual Basic Scripting Edition
Contents What Is VBScript? ........................................................................................................2 Summary ...............................................................................................................2 VBScript................................................................................................................2 VBScript Data Types ....................................................................................................3 What are the VBScript Data Types? .....................................................................3 Conversion Functions....................................................................................................5 CInt Function ............................................................................................................5 VBScript Variables .......................................................................................................6 What Is a Variable?...............................................................................................6 Declaring Variables...............................................................................................6 Naming Restrictions..............................................................................................7 Scope and Lifetime of Variables ...........................................................................7 Assigning Values to Variables ..............................................................................7 Scalars and Arrays.................................................................................................8 VBScript Constants.....................................................................................................10 What Is a Constant? ............................................................................................10 Creating Constants ..............................................................................................10 VBScript Operators.....................................................................................................11 Operator Precedence ...........................................................................................11 Controlling Program Flow in VBScript ......................................................................13 Controlling Program Execution ..........................................................................13 Making Decisions Using If...Then...Else ............................................................13 Using Loops to Repeat Code...............................................................................14 Using Do Loops ..................................................................................................15 Repeating a Statement Until a Condition Becomes True....................................16 Exiting a Do...Loop Statement from Inside the Loop .........................................17 Using While...Wend............................................................................................17 Using For...Next..................................................................................................18 VBScript Procedures...................................................................................................20 Kinds of Procedures ............................................................................................20 Function Procedures............................................................................................20 Getting Data into and out of Procedures .............................................................21 Using Sub and Function Procedures in Code......................................................22 VBScript Coding Conventions....................................................................................23 What Are Coding Conventions? .........................................................................23 Constant Naming Conventions ...........................................................................23 Variable Naming Conventions............................................................................24 Variable Scope ....................................................................................................24 Variable Scope Prefixes ......................................................................................24 Descriptive Variable and Procedure Names .......................................................25 Object Naming Conventions ...............................................................................25 Code Commenting Conventions .........................................................................26 Formatting Your Code ........................................................................................27
Page 1 of 27
What Is VBScript?
Summary
Here you'll find a description of Microsoft Visual Basic Scripting Edition (VBScript). In the other tutorial sections, you'll learn about variables, constants, and procedures.
VBScript
VBScript, the newest member of the Visual Basic family of programming languages, brings active scripting to a wide variety of environments, including Web client scripting in Microsoft Internet Explorer version 3.0 and Web server scripting in Microsoft Internet Information Server version 3.0. Easy to Use and Learn If you already know Visual Basic or Visual Basic for Applications, VBScript will be very familiar. Even if you don't know Visual Basic, once you learn VBScript, you're on your way to programming with the whole family of Visual Basic languages. Although you can learn about VBScript in just these few Web pages, they don't teach you how to program. To get started programming, take a look at Step by Step books available from Microsoft Press. ActiveX Scripting VBScript talks to host applications using ActiveX Scripting. With ActiveX Scripting, browsers and other host applications don't require special integration code for each scripting component. ActiveX Scripting enables a host to compile scripts, obtain and call entry points, and manage the namespace available to the developer. With ActiveX Scripting, language vendors can create standard language run times for scripting. Microsoft will provide run-time support for VBScript. Microsoft is working with various Internet groups to define the ActiveX Scripting standard so that scripting engines can be interchangable. ActiveX Scripting is used in Microsoft Internet Explorer 3.0 and in Microsoft Internet Information Server 3.0. VBScript in Other Applications and Browsers As a developer, you may license VBScript's source implementation at no charge for use in your products. Microsoft provides binary implementations of VBScript for the 32-bit Windows API, the 16-
Page 2 of 27
bit Windows API, and the Macintosh. VBScript is integrated with World Wide Web browsers. VBScript and ActiveX Scripting can also be used as a general scripting language in other applications.
Page 3 of 27
The following table shows the various subtypes of data that a Variant can contain. Subtype Empty Null Boolean Byte Integer Currency Long Single Description Variant is uninitialized. Value is either 0 for numeric variables or a zero-length string ("") for string variables. Variant intentionally contains no valid data. Contains either True or False. Contains integer in the range 0 to 255. Contains integer in the range -32,768 to 32,767. -922,337,203,685,477.5808 to 922,337,203,685,477.5807. Contains integer in the range -2,147,483,648 to 2,147,483,647. 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. Contains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. Contains a number that represents a date between January 1, 100 to December 31, 9999. Contains a variable-length string that can be up to approximately 2 billion characters in length. Contains an object. Contains an error number.
Double
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.
Page 4 of 27
Conversion Functions
Asc Function CBool Function CByte Function CCur Function CDate Function CDbl Function Chr Function CInt Function CLng Function CSng Function CStr Function Hex Function Oct Function
CInt Function
Description Returns an expression that has been converted to a Variant of subtype Integer. Syntax CInt(expression ) The expression argument is any valid expression. Remarks In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or doubleprecision arithmetic normally would occur. Use the CInt function to provide internationally aware conversions from any other data type to an Integer subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators. If expression lies outside the acceptable range for the Integer subtype, an error occurs.
Page 5 of 27
VBScript 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:
Page 6 of 27
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.
B = 200
Page 7 of 27
Dim A(10)
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.
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:
. . . SomeVariable = A(8) . . .
Arrays aren't limited to a single dimension. You can have as many of 60 dimensions although most people can't comprehend more
Page 8 of 27
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 twodimensional array consisting of 6 rows and 11 columns:
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:
Page 9 of 27
VBScript Constants
What Is a Constant?
A constant is a meaningful name that takes the place of a number or string and never changes. VBScript currently has no constants defined by the language. In VBScript, constants are implemented as literal values assigned to variable names.
Creating Constants
You create constants in VBScript using the Const statement. Using the Const statement, you can create string or numeric constants with meaningful names. You can then assign them literal values and use them in your script. For example: Const MyString MyString = "This is my string." Const MyAge MyAge = 49 Note that the string literal is enclosed in quotation marks (" "). Quotation marks are the most obvious way to differentiate string values from numeric values. Date literals and time literals can be represented by nclosing them in number signs (#). For example:
Page 10 of 27
VBScript Operators
Operator Precedence
VBScript has a full range of operators, including arithmetic operators, comparison operators, concatenation operators, and logical operators. When several operations occur in an expression, each part is evaluated and resolved in a predetermined order. That order is known as operator precedence. You can use parentheses to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, normal operator precedence is maintained. When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left to right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence. Arithmetic Description Exponentiation Unary negation Multiplication Division Integer division Modulus arithmetic Addition Subtraction String concatenation Symbol ^ * / \ Mod Comparison Description Equality Inequality Less than Greater than Less than or equal to Greater than or equal to Object equivalence Symbol = <> < > <= >= Logical Description Logical negation Logical conjunction Logical disjunction Logical exclusion Logical equivalence Logical implication Symbol Not And Or Xor Eqv Imp
+ &
Is
Page 11 of 27
When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right. The string concatenation operator (&) is not an arithmetic operator, but in precedence it does fall after all arithmetic operators and before all comparison operators. The Is operator is an object reference comparison operator. It does not compare objects or their values; it checks only to determine if two object references refer to the same object.
Page 12 of 27
Sub FixDate() Dim myDate myDate = #2/13/95# If myDate < Now Then myDate = Now End Sub
If you want to run more than one line of code, you must use the multiple line syntax. This syntax includes the End If statement, as shown in the following example:
Sub AlertUser(value) If value = 0 Then AlertLabel.ForeColor = vbRed AlertLabel.Font.Bold = True AlertLabel.Font.Italic = True End If End Sub
Page 13 of 27
Running Certain Statements if a Condition is True, and Running Others if it is False You can use an If...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the condition is False.
Sub AlertUser(value) If value = 0 Then AlertLabel.ForeColor = vbRed AlertLabel.Font.Bold = True AlertLabel.Font.Italic = True Else AlertLabel.Forecolor = vbBlack AlertLabel.Font.Bold = False AlertLabel.Font.Italic = False End If End Sub
Page 14 of 27
Using Do Loops
You can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True. Repeating Statements While a Condition is True Use the While keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the first example following this paragraph), or you can check it after the loop has run at least once (as shown in the second example). In the ChkFirstWhile procedure, if myNum were set to 9 instead of 20, the statements inside the loop would never run. In the ChkLastWhile procedure, the statements inside the loop run only once because the condition is already False.
Sub ChkFirstWhile() Dim counter, myNum counter = 0 myNum = 20 Do While myNum > 10 myNum = myNum - 1 counter = counter + 1 Loop MsgBox "The loop made " & counter & " repetitions." End Sub Sub ChkLastWhile() Dim counter, myNum counter = 0 myNum = 9 Do myNum = myNum - 1 counter = counter + 1 Loop While myNum > 10 MsgBox "The loop made " & counter & " repetitions." End Sub
Page 15 of 27
Sub ChkFirstUntil() Dim counter, myNum counter = 0 myNum = 20 Do Until myNum = 10 myNum = myNum - 1 counter = counter + 1 Loop MsgBox "The loop made " & counter & " repetitions." End Sub Sub ChkLastUntil() Dim counter, myNum counter = 0 myNum = 1 Do myNum = myNum + 1 counter = counter + 1 Loop Until myNum = 10 MsgBox "The loop made " & counter & " repetitions." End Sub
Page 16 of 27
Sub ExitExample() Dim counter, myNum counter = 0 myNum = 9 Do Until myNum = 10 myNum = myNum - 1 counter = counter + 1 If myNum < 10 Then Exit Do Loop MsgBox "The loop made " & counter & " repetitions." End Sub
Using While...Wend
The While...Wend statement is provided in VBScript for those who are familiar with its usage. However, because of the lack of flexibility in While...Wend, it is recommended that you use Do...Loop instead.
Page 17 of 27
Using For...Next
You can use For...Next statements to run a block of statements a specific number of times. For loops, use a counter variable whose value is increased or decreased with each repetition of the loop. For example, the following procedure causes a procedure called MyProc to execute 50 times. The For statement specifies the counter variable x and its start and end values. The Next statement increments the counter variable by 1.
Sub TwosTotal() Dim j, total For j = 2 To 10 Step 2 total = total + j Next MsgBox "The total is " & total End Sub
To decrease the counter variable, you use a negative Step value. When doing so, you must specify an end value that is less than the start value. In the following example, the counter variable myNum is decreased by 2 each time the loop repeats. When the loop is finished, total is the sum of 16, 14, 12, 10, 8, 6, 4, and 2.
Page 18 of 27
Sub NewTotal() Dim myNum, total For myNum = 16 To 2 Step -2 total = total + myNum Next MsgBox "The total is " & total End Sub
You can exit any For...Next statement before the counter reaches its end value by using the Exit For statement. Because you usually want to exit only in certain situations, such as when an error occurs, you should use the Exit For statement in the True statement block of an If...Then...Else statement. If the condition is False, the loop runs as usual.
Page 19 of 27
VBScript Procedures
Kinds of Procedures
In VBScript there are two kinds of procedures; the Sub procedure and the Function procedure. Sub Procedures A Sub procedure is a series of VBScript statements, enclosed by the Sub and End Sub statements, that performs actions but doesn't return a value. A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses. The following Sub procedure uses two intrinsic, or built-in, VBScript functions, MsgBox and InputBox, to prompt a user for some information. It then displays the results of a calculation based on that information. The calculation is performed in a Function procedure created using VBScript. The Function procedure is shown in the following discussion.
Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C." End Sub
Function Procedures
A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant. In the following example, the Celsius function calculates degrees Celsius from degrees Fahrenheit. When the function is called from the ConvertTemp Sub procedure, a variable containing the argument value is passed to the function. The result of the
Page 20 of 27
Sub ConvertTemp() temp = InputBox("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C." End Sub Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function
To get data out of a procedure, you must use a Function. Remember, a Function procedure can return a value; a Sub procedure can't.
Page 21 of 27
Temp = Celsius(fDegrees)
or
MsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."
To call a Sub procedure from another procedure, you can just type the name of the procedure along with values for any required arguments, each separated by a comma. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses.
The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing.
Page 22 of 27
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. Using good coding conventions results in precise, readable, and unambiguous source code that is consistent with other language conventions and as intuitive as possible.
USER_LIST_MAX NEW_LINE
Page 23 of 27
Variable Scope
Variables should always be defined with the smallest scope possible. VBScript variables can have the following scope. Scope Procedurelevel Script-level Where Variable Is Declared Event, Function, or Sub procedure HEAD section of an HTML page, outside any procedure Visibility Visible in the procedure in which it is declared. Visible in every procedure in the script.
Page 24 of 27
Page 25 of 27
Return Values
Remember the following points: 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.
Page 26 of 27
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
Page 27 of 27