1.

Introduction
VBScript stands for Visual Basic Script, a scripting language developed by Microsoft to be used with Microsoft products, mainly Internet Explorer.

VBScript Data types:
VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it is used. Because Variant is the only data type in VBScript, it is also the data type returned by all functions in VBScript. At its simplest, a Variant can contain either numeric or string information. A Variant behaves as a number when you use it in a numeric context and as a string when you use it in a string context. That is, if you are working with data that looks like numbers, VBScript assumes that it is numbers and does what is most appropriate for numbers. Similarly, if you're working with data that can only be string data, VBScript treats it as string data. You can always make numbers behave as strings by enclosing them in quotation marks (" ").

a. Variant Subtypes:
The following table shows the subtypes of data that a Variant can contain. Subtype Empty Null Boolean Byte Integer Description Variant is uninitialized. Value is 0 for numeric variables or a zerolength 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.

Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807. Long Single 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.94065645841247E-324 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.

Double

Date (Time)

VB Scripting

1

String Object Error

Contains a variable-length string that can be up to approximately 2 billion characters in length. Contains an object. Contains an error number.

You can use conversion functions to convert data from one subtype to another. In addition, the VarType function returns information about how your data is stored within a Variant.

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.

b. 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

c. 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.

d. 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:

VB Scripting

2

B = 200

e. Array Variables:
Sometimes you want to assign more than one value to a single variable. Then you can create a variable that can contain a series of values. This is called an array variable. The declaration of an array variable uses parentheses ( ) following the variable name. In the following example, an array containing 3 elements is declared: Dim names(2) The number shown in the parentheses is 2. We start at zero so this array contains 3 elements. This is a fixed-size array. You assign data to each of the elements of the array like this: names(0)="Tove" names(1)="Jani" names(2)="Stale" Similarly, the data can be retrieved from any element using the index of the particular array element you want. Like this: mother=names(0) You can have up to 60 dimensions in an array. Multiple dimensions are declared by separating the numbers in the parentheses with commas. Here we have a two-dimensional array consisting of 5 rows and 7 columns: dim table(4, 6)

2. CONSTANTS:
A constant is a meaningful name that takes the place of a number or string and never changes. VBScript defines a number of intrinsic constants a. Creating Constants You create user-defined constants in VBScript using the Const statement; you can create string or numeric constants with meaningful names and assign them literal values. For example:

VB Scripting

3

display only a date. For example: Const CutoffDate = #6-1-97# Here are the various categories of constants provided in VBScript and a brief description of each:         • Color Constants Date and Time Constants Date Format Constants Miscellaneous Constants MsgBox Constants String Constants Tristate Constants VarType Constants Color Constants Defines eight basic colors that can be used in scripting." Const MyAge = 49 Note that the string literal is enclosed in quotation marks (" "). For real numbers. If there is no fractional part. VB Scripting 4 . display time only. EXAMPLES Constant vbSunday vbMonday • Value Description 1 Sunday 2 Monday Date Format Constants Defines constants used to format dates and times. Date and time display is determined by your system settings. EXAMPLES Constant vbBlack VbRed • Value &h00 &hFF Description Black Red Date and Time Constants Defines date and time constants used by various date and time functions. Quotation marks are the most obvious way to differentiate string values from numeric values. If there is no integer part. You represent Date literals and time literals by enclosing them in number signs (#). EXAMPLES Constant VbGeneralDate 0 Value Description Display a date and/or time. display a date and time.Const MyString = "This is my string.

for example. Retry. and Ignore buttons. not useful in Microsoft Windows. EXAMPLES VB Scripting 5 . • Miscellaneous Constants Defines constants that don't conveniently fit into any other category. EXAMPLES Constant vbObjectError Value -2147221504 Description User-defined error numbers should be greater than this value.Raise Number = vbObjectError + 1000 • MsgBox Constants Defines constants used in the MsgBox function to describe button visibility. labeling. Display Abort. Display OK and Cancel buttons. EXAMPLES Constant vbCr VbCrLf vbFormFeed Value Chr(13) Chr(13) & Chr(10) Chr(12) Carriage return. Description • Tristate Constants Defines constants used with functions that format numbers. Form feed. Err. EXAMPLES Constant vbOKOnly vbOKCancel vbAbortRetryIgnore • Value 0 1 2 Description Display OK button only.VbLongDate 1 Display a date using the long date format specified in your computer's regional settings. String Constants Defines a variety of non-printable characters used in string manipulation. Carriage return–linefeed combination. EXAMPLES Constant vbUseDefault vbTrue vbFalse Value Description -2 Use default from computer's regional settings. behavior. and return values. -1 True 0 False • VarType Constants Defines the various Variant subtypes.

Error Number 429 507 449 17 430 506 11 An exception occurred Argument not optional Can't perform requested operation Class doesn't support Automation Class not defined Division by zero Description ActiveX component can't create object b) VB SCRIPT SYNTAX ERRORS: VBScript syntax errors are errors that result when the structure of one of your VBScript statements violates one or more of the grammatical rules of the VBScript scripting language. VBScript run-time errors occur while your script is being executed. Error Number 1053 1005 1021 1047 1014 1015 1010 1012 Description Class initialize or terminate do not have arguments Expected '(' Expected 'Case' Expected 'Class' Expected 'End' Expected 'Function' Expected identifier Expected 'If' VB Scripting 6 .Constant vbEmpty vbNull vbInteger 3. VBScript syntax errors occur during the program compilation stage. VBScript Run-time Errors 2. before the program has begun to be executed. ERRORS: Value Description 0 Uninitialized (default) 1 Contains no valid data 2 Integer subtype There are two types of error 1. and memory is being dynamic allocated. when variable expressions are being evaluated. VBScript Syntax Errors A) VB SCRIPT RUN-TIME ERRORS: VBScript run-time errors are errors that result when your VBScript script attempts to perform an action that the system cannot execute.

and other mathematical operations on numbers and variables use the operators listed below. or some other type of relationship use the comparison operators listed below. Operator = > < >= <= <> English Equal To Greater Than Less Than Greater Than Or Equal To Less Than Or Equal To Not Equal To Example 10 =1 4 10 > 14 10 < 14 10 >= 14 10 <= 14 10 <> 14 Result False False True False True 5 3. if they're equal. VBScript Operators: Comparison When you want to compare two numbers to see which is bigger. multiplication. subtraction.1019 1020 Expected 'Loop' Expected 'Next' 4. Operators: Operators are used to "do operations" or manipulate variables and values. VBScript Operators: Logic Logic operators are used to manipulate and create logical statements. VBScript Operators: Math When you want to perform addition. Operator + * / ^ Mod English Add Subtract Multiply Divide Exponent Modulus Example 8+7 11-10 7*8 8/2 2^4 15 Mod 10 Result 15 1 56 4 16 5 2.VBScript's many operators can be separated into four semi-distinct categories: • • • • Math Operators Comparison Operators Logic Operators String Concatenation Operator 1. Common uses of comparison operators are within conditional statements like an If Statement or the condition check in a While Loop. For example if you wanted a variable shoeSize to be equal to 10 or 11 then you would do something like: VB Scripting 7 .

but we do have a list of the various logic operators available to you in VBScript.then...then. VBScript String Concatenation Operator When you have various strings that you would like to combine into one string use the concatenation operator. write function. String concatenation is often used when using the document. Operator & English Connected To Example "Hello" & " there" Result "Hello there" Be sure to bookmark this page so that you can use it as a reference if you forget the various operators available in VBScript.else statement if. 5.VBScript Code: <script type="text/vbscript"> Dim shoeSize showSize = 10 If showSize = 10 Or shoeSize = 12 Then 'Some code EndIf </script> A detailed explanation of Logic and Logic Operators are beyond the scope of this tutorial. Conditional Statements Very often when you write code...... Operator Not Or And English Inverts Truth Value Either Can Be True Both Must Be True Example Not False True Or False True And False Result True True False 4. effectively making them into one string. In VBScript we have four conditional statements: • • • if statement if.elseif statement VB Scripting 8 . you want to perform different actions for different decisions. You can use conditional statements in your code to do this.. The concatenation operator acts as glue between the two or more strings you wish to attach.

then.then. if...elseif statement This statement is used to select one of many sets of lines to execute VB Scripting 9 . you must put each statement on separate lines and end the statement with the keyword "End If": if i=10 Then msgbox "Hello" i = i+1 end If 2. if. If statement This statement is used to execute a set of code when a condition is true if i=10 Then msgbox "Hello" There is no . If you want to execute more than one statement when a condition is true..... 3.. and the other block will be executed otherwise (if i is not equal to 10)...• select case statement – 1. You just tell the code to perform one action if the condition is true (in this case if i=10).. in this syntax.else statement This statement used to select one of two sets of line to execute if i=10 then msgbox "Hello" else msgbox "Goodbye" end If The first block of code will be executed if the condition is true.else.

the block of code associated with that Case is executed. that is evaluated once. VB Scripting 10 .if payment="Cash" then msgbox "You are going to pay cash!" elseif payment="Visa" then msgbox "You are going to pay with visa." else msgbox "Unknown method of payment." elseif payment="AmEx" then msgbox "You are going to pay with American Express. The value of the expression is then compared with the values for each Case in the structure. If there is a match. Select Case The SELECT statement is used to select one of many blocks of code to execute: select case payment case "Cash" msgbox "You are going to pay cash" case "Visa" msgbox "You are going to pay with visa" case "AmEx" msgbox "You are going to pay with American Express" case Else msgbox "Unknown method of payment" end select This is how it works: First we have a single expression (most often a variable)." end If 6.

In VBScript we have four looping statements: • • • For. You must specify an end value that is less than the start value.. like this: For i=1 to 10 some code Next The For statement specifies the counter variable (i) and its start and end values. We can use looping statements in our code to do this. VB Scripting 11 .Loop statement 1. the counter variable (i) is increased by two each time the loop repeats.7.Next Loop It runs statements a specified number of times. you must use a negative Step value. Step Keyword Using the Step keyword.. The Next statement increases the counter variable (i) by one. you can increase or decrease the counter variable by the value you specify. In the example below. For. For i=2 To 10 Step 2 some code Next To decrease the counter variable.Next statement For Each..... You can use a counter variable that increases or decreases with each repetition of the loop... we want the same block of code to run a number of times. Looping Statements: When we write code.Next statement Do.

. For i=10 To 2 Step -2 some code Next 2.Next You can exit a For.. Exit a For. Do. dim cars(2) cars(0)="Volvo" cars(1)="Saab" cars(2)="BMW" For Each x in cars document.Loop It loops while or until a condition is true We can use Do....write(x & "<br />") Next 4.. The block of code is repeated while a condition is true or until a condition becomes true..Next Loop It runs statements for each item in a collection or each element of an array A For Each.Next statement with the Exit For keyword.Next loop repeats a block of code for each item in a collection.In the example below.. or for each element of an array. Do While i>10 VB Scripting 12 .. the counter variable (i) is decreased by two each time the loop repeats.Loop statements to run a block of code when we do not know how many repetitions we want. For Each. Repeating Code While a Condition is True The While keyword is used to check a condition in a Do.. 3..Loop statement....

the code inside the loop will never be executed..Loop statement with the Exit Do keyword.. even if i is equal to 10. even if i is less than 10.. the code inside the loop above will never be executed. Do some code Loop While i>10 The code inside this loop will be executed at least one time..Loop statement.some code Loop If i equals 9. Exit a Do. Repeating Code Until a Condition Becomes True The Until keyword is used to check a condition in a Do. Do some code Loop Until i=10 The code inside this loop will be executed at least one time. Do Until i=10 some code Loop If i equals 10. 5.. Do Until i=10 i=i-1 If i<10 Then Exit Do Loop VB Scripting 13 .Loop we can exit a Do..

Defining and Invoking Function Procedures A "Function" statement defines a function procedure with the following syntax: Function function_name(argument_list) statement_block function_name = return_value End Function Where "function_name" is the name of the function. VB offers two types of procedures: 1. Defining a procedure. and as long as i is greater than 10. 2. If not given. "argument_list" a list of variables used to pass data into and/or out of the function. Invoking a procedure. default value will be returned to the invoking statements. function_name(argument_list) . Sub Procedure . "argument_list" is optional. But it can be executed by an invoking statement in the main execution code.The code inside this loop will be executed as long as i is different from 10..A procedure that returns a value explicitly. 8.. Procedures: A Procedure is a unit of code outside of the main execution code. Just use the function name with an argument list in any expression: . 2. and "return_value" is the value to be returned explicitly to the invoking statements.. There are 3 aspects about procedures: 1. But this is not recommended. no need of any special statements. Function Procedure . Exchanging data between the main execution code and a procedure.. Assigning the return value to the function name is also optional. Of course.A procedure that does not return any value explicitly. Invoking a function procedure is simple. 3. This will cause the system to: VB Scripting 14 .

you can use the "Exit" statement: Exit Function Function Procedure Example d = F2C(70.32. Continue to evaluate the expression. Execute the entire statement block defined inside the function. Map data or variables based on the argument list.writeln("") document.1111111111111 VB Scripting 15 .writeln("Received Celsius = " & d) Function F2C(dFahrenheit) document.0) document.0 ) / 1. If you want terminate a function procedure early.writeln("Converting Fahrenheit = " & dFahrenheit) dCelsius = (dFahrenheit .8 document.0) document.writeln("Received Celsius = " & d) d = F2C(212. Take the value returned in the function name.writeln("Returning Celsius = " & dCelsius) F2C = dCelsius End Function Here is the output: Converting Fahrenheit = 70 Returning Celsius = 21.Stop evaluating the expression.1111111111111 Received Celsius = 21.

Converting Fahrenheit = 212 Returning Celsius = 100 Received Celsius = 100 9. Execute the entire statement block defined inside the subroutine. Of course. Explicit call with subroutine name: sub_name argument_list Both syntaxes will cause the system to: Stop execution in main code flow. and "argument_list" a list of variables used to pass data into and/or out of the subroutine. Invoking a subroutine is different than a function procedure. Continue to execute main code flow. Defining and Invoking Sub Procedures A Sub Procedure is similar to a function procedure. It can be defined with the "Sub" statement: Sub sub_name(argument_list) statement_block End Sub where "sub_name" is the name of the sub procedure (subroutine). If we want terminate a sub procedure early. "argument_list" is optional. Notice that subroutine does not return any values. Map data or variables based on the argument list. Explicit call with "Call" statement: Call sub_name(argument_list) 2. You can use one of the two syntaxes below: 1. you can use the "Exit" statement: Exit Sub VB Scripting 16 .

In this case. By default. VB Scripting 17 . But. Any changes to that data will not affect the original data in the calling code. the procedure will get a copy of the array. an argument name can be used as a variable that referring (sharing) the same data as the calling code. Of course. because the procedure only gets a copy of the data. A pass-by-value argument is safer than a pass-by-reference argument. 6. if you put the key word "ByVal" before the argument name. 4. an argument name can be used as a variable that contains a copy of the data provided by the calling code. This allows the procedure to output data back to the calling code. you put the word "ByRef" before an argument name to declare a pass-byreference argument explicitly. passing arguments to procedures seems to be a simple job. arguments are passed by reference. A pass-by-reference argument can be used to allow the procedure to alter data that is associated with a variable in the calling code. 8. arguments can be passed by value. In this case. Arrays can be passed by reference. VB script has the following rules on passing arguments to procedures: 1. In this case. 2. Arrays can also be passed by value. But it may cause confusion if you don't following the rules. Rules of Passing Arguments As shown in previous examples.Sub Procedure Example Call Hello("Tom") Hello "Herong" Sub Hello(sName) document. 7. 5.writeln("Helo " & sName) End Sub Here is the output: Helo Tom Helo Herong. I don't know how to specify an array as the return value of a function procedure. 3.writeln("") document.

writeln(" Before Sub: " & "Apple" & " | " & "Orange") Call SwapByRef("Apple". "Orange") document.writeln("") document. ByRef vRight) vTemp = vLeft vLeft = vRight vRight = vTemp document.writeln(" After Sub: " & "Apple" & " | " & "Orange") vFirst = "Dog" vSecond = "Cat" document.Example .writeln(" In Sub: " & vLeft & " | " & vRight) End Sub Here is the output: Test 1: Swapping two literals by reference Before Sub: Apple | Orange In Sub: Orange | Apple After Sub: Apple | Orange VB Scripting 18 .writeln(" Before Sub: " & vFirst & " | " & vSecond) Call SwapByRef(vFirst.Passing Arguments by Reference document.writeln("Test 2: Swapping two variables by reference") document.writeln(" After Sub: " & vFirst & " | " & vSecond) Sub SwapByRef(ByRef vLeft.writeln("") document. vSecond) document.writeln("Test 1: Swapping two literals by reference") document.

"Orange") document. ByVal vRight) vTemp = vLeft vLeft = vRight VB Scripting 19 .writeln(" Before Sub: " & vFirst & " | " & vSecond) Call SwapByVal(vFirst.writeln("") document.writeln("Test 2: Swapping two variables by value") document. vSecond) document.Test 2: Swapping two variables by reference Before Sub: Dog | Cat In Sub: Cat | Dog After Sub: Cat | Dog Test 1 shows that data literal can be used for a "ByRef" argument.writeln(" After Sub: " & vFirst & " | " & vSecond) Sub SwapByVal(ByVal vLeft. "ByRef" keyword is optional. Test 2 shows that using variable for a "ByRef" argument lets to receive the change by the subroutine. Example .writeln("Test 1: Swapping two literals by value") document. After the subroutine call.writeln(" After Sub: " & "Apple" & " | " & "Orange") vFirst = "Dog" vSecond = "Cat" document. values in vFirst and vSecond have been swapped.writeln("") document.Passing Arguments by Value document.writeln(" Before Sub: " & "Apple" & " | " & "Orange") Call SwapByVal("Apple". By which we will not be able to receive the change done by the subroutine.

writeln("") document.writeln(" In Sub: " & vLeft & " | " & vRight) End Sub Here is the output: Test 1: Swapping two literals by value Before Sub: Apple | Orange In Sub: Orange | Apple After Sub: Apple | Orange Test 2: Swapping two variables by value Before Sub: Dog | Cat In Sub: Cat | Dog After Sub: Dog | Cat Here are my comments about this example: Test 1 is useless. the procedure is working on the same array as the calling code. the procedure is working on a independent copy of the array in the calling code. arrays can also be passed as arguments. "Rabbit") document.writeln("Test 1: Reversing a data literal") bOk = ReverseArray("Apple") aPets = Array("Bird". "Cat". Test 2 shows that "ByVel" arguments will not bring any changes back to the calling code. "Fish".writeln("") VB Scripting 20 . After the subroutine call. If an array is passed by reference. example code of using array as an argument document. If an array is passed by value.vRight = vTemp document. Passing Array as Arguments As I mentioned earlier. values in vFirst and vSecond have not been changed at all. "Dog". 10.

writeln(" After Sub: " & Join(aPets)) Function ReverseArray(ByRef aList) If IsArray(aList) Then iMin = LBound(aList) iMax = UBound(aList) For i=iMin to iMax\2 j = iMax .(i-iMin) vTemp = aList(i) aList(i) = aList(j) aList(j) = vTemp Next ReverseArray = True Else document.") ReverseArray = False End If End Function Here is the output: Test 1: Reversing a data literal Error: You are not giving an array.document.writeln(" Before Sub: " & Join(aPets)) bOk = ReverseArray(aPets) document. Test 2: Reversing an array Before Sub: Bird Cat Dog Fish Rabbit VB Scripting 21 .writeln("Error: You are not giving an array.writeln("Test 2: Reversing an array") document.

Collision . You can take it a utility function to your application. The bad thing about rule #2 is that if you are using temporary variable in a procedure without explicit declaration. variable scope gets more complex. the variable of the main code become in-accessible within this procedure. 2. Variable Scope in Procedures Variable Scope . Global . its scope is from the statement where it is defined to the last statement of the entire code including all procedures. if you declare all temporary variables explicitly in procedures. 11. you could accidentally change the value of a global variable of the same name. There are some interesting consequences of those rules: The nice thing about rule #1 is that variables defined the main code are automatically accessible in all procedures.If a variable is explicitly defined in a procedure code has the same name as a variable defined in the main code. 3.The area of source code where a variable is accessible. If you are not using procedures.If a variable is defined in the main code.If a variable is defined in a procedure code. Rule #3 helps us to avoid the bad impact of rule #3.Variable Scopes Dim vGlobalDim vGlobalDim = "Cat" vGlobalNoDim = "Dog" Dim vTempDim vTempDim = "Bird" VB Scripting 22 . The scope of a variable is: from the statement where it is defined to the last statement of the code. its scope is from the statement where it is defined to the last statement of the procedure. Here are some basic rules: 1. You don't have to pass them as reference arguments to share them in a procedure.After Sub: Rabbit Fish Dog Cat Bird My "ReverseArray" function worked perfectly. Example . If you are using procedures. variable scope is very simple. Local .

writeln(" vLocalDim = " & vLocalDim) document.writeln(" vGlobalDim = " & vGlobalDim) document.vTempNoDim = "Fish" Call ScopeCheck() document.writeln(" vTempDim = " & vTempDim) document.Updated by Sub" vGlobalNoDim = vGlobalNoDim & " .writeln("Current value after Sub:") document.writeln(" vGlobalNoDim = " & vGlobalNoDim) document.Updated by Sub" VB Scripting 23 .Updated by Sub" vLocalDim = vLocalDim & " .writeln(" vTempNoDim = " & vTempNoDim) Sub ScopeCheck() Dim vLocalDim vLocalDim = "Apple" vLocalNoDim = "Orange" Dim vTempDim vTempDim = "Banana" vTempNoDim = "Grape" ' Updating values vGlobalDim = vGlobalDim & " .writeln("") document.Updated by Sub" vLocalNoDim = vLocalNoDim & " .writeln(" vLocalNoDim = " & vLocalNoDim) document.

writeln("Current value in Sub:") document.Updated by Sub" vTempNoDim = vTempNoDim & " .Updated by Sub" ' Showing values document.Updated by Sub Current value after Sub: vGlobalDim = Cat .writeln(" vTempNoDim = " & vTempNoDim) End Sub Here is the output: Current value in Sub: vGlobalDim = Cat .Updated by Sub vLocalDim = Apple .writeln(" vLocalNoDim = " & vLocalNoDim) document.writeln("") document.Updated by Sub vTempNoDim = Grape .Updated by Sub vGlobalNoDim = Dog .writeln(" vGlobalNoDim = " & vGlobalNoDim) document.Updated by Sub vTempDim = Banana .Updated by Sub vLocalNoDim = Orange .writeln(" vTempDim = " & vTempDim) document.writeln(" vLocalDim = " & vLocalDim) document.Updated by Sub vGlobalNoDim = Dog .Updated by Sub VB Scripting 24 .writeln(" vGlobalDim = " & vGlobalDim) document.vTempDim = vTempDim & " .

Coding conventions can include the following: • • • Naming conventions for objects. vGlobalNoDim. CODING CONVENTIONS: Coding conventions are suggestions that may help you write code using Microsoft Visual Basic Scripting Edition. This is why vTempDim still has the old value after the subroutine call. and unambiguous source code that is consistent with other language conventions and as intuitive as possible. and accessible in the procedure. vTempDim. variables. "Dim" or not makes no difference. Constant Naming Conventions Constant names should be uppercase with underscores ( _ ) between words. not accessible in the main code. define in the procedure. vLocalNoDim. The behavior of vGlobalDim and vGlobalNoDim is pretty consistent. and procedures Commenting conventions Text formatting and indenting guidelines 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. Notice that vLocalDim and vLocalNoDim are empty in the "after Sub" message. 12.vLocalDim = vLocalNoDim = vTempDim = Bird vTempNoDim = Grape . readable. Using good coding conventions results in precise. The behavior of vTempDim and vTempNoDim shows that "Dim" statement forces vTempDim to a new local variable. and one in the procedure. defined in the main code. For example: USER_LIST_MAX NEW_LINE VB Scripting 25 . one in the main code. So we have two variables of the same name. and vTempNoDim. The behavior of vLocalDim and vLocalNoDim is also consistent.Updated by Sub There are 6 variables in this example: vGlobalDim. vLocalDim.

so does the value of being able to quickly differentiate the scope of variables. Scope Procedure-level Prefix None Example dblVelocity VB Scripting 26 . Function. Visible in every procedure in the script. Scope Procedurelevel Script-level Where Variable Is Declared Event. Variable Scope Prefixes As script size grows. A one-letter scope prefix preceding the type prefix provides this. outside any procedure Visibility Visible in the procedure in which it is declared. along with descriptive names for variables in your VBScript code. VBScript variables can have the following scope.Variable Naming Conventions For purposes of readability and consistency. use the prefixes listed in the following table. Subtype Boolean Byte Date (Time) Double Error Integer Long Object Single String Prefix bln byt dtm dbl err int lng obj sng str Example blnFound bytRasterData dtmStart dblTolerance errOrderNum intQuantity lngDistance objCurrent sngAverage strFirstName Variable Scope Variables should always be defined with the smallest scope possible. or Sub procedure HEAD section of an HTML page. without unduly increasing the size of variable names.

Object Naming Conventions The following table lists recommended conventions for the various objects you may encounter while programming VBScript. make sure they are consistent throughout the entire script. For example. When using abbreviations. procedure names should begin with a verb. In addition. drop-down list box Command button Common dialog Frame Horizontal scroll bar Image Label Line List Box Spin Text box Vertical scroll bar Prefix pnl ani chk cbo cmd dlg fra hsb img lbl lin lst spn txt vsb Example pnlGroup aniMailBox chkReadOnly cboEnglish cmdExit dlgFileOpen fraLanguage hsbVolume imgIcon lblHelpMessage linVertical lstPolicyCodes spnPages txtLastName vsbRate VB Scripting 27 . variable names greater than 32 characters can be difficult to read. standard abbreviations are recommended to help keep name length reasonable.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. such as InitNameArray or CloseDialog. In general. Object type 3D Panel Animated button Check box Combo box. For frequently used or long terms. randomly switching between Cnt and Count within a script or set of scripts may lead to confusion.

dialog boxes. Remember the following points: Every important variable declaration should include an inline comment describing the use of the variable being declared. procedures. control. List of the procedure's effect on each external variable. Explanation of each argument that isn't obvious. while still allowing code formatting to reflect logic structure and nesting. and procedures should be named clearly enough that inline comments are only needed for complex implementation details. 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. Here are a few pointers: VB Scripting 28 . Sometimes a piece of pseudo code describing the algorithm can be helpful. controls. erroneous comments. or worse yet. For examples. Each argument should be on a separate line with inline comments. Formatting Your Code: Screen space should be conserved as much as possible. List of any external variable. you should include an overview that describes the script. and other system dependencies. or other element whose state affects this procedure. enumerating objects. algorithms. At the beginning of your script. Variables. Explanation of the value returned. Section Heading Purpose Assumptions Effects Inputs Return Values Comment Contents What the procedure does (not how). should also be described at the beginning of each procedure. The code itself and any necessary inline comments describe the implementation. control. resulting in unnecessary comment maintenance work. Procedure header comments should include the following section headings. This description should not describe the implementation details (how it does it) because these often change over time. especially through reference arguments. or other element. see the section "Formatting Your Code" that follows. Function return values and other variables that are changed by the procedure.Slider sld sldScale Code Commenting Conventions All procedures should begin with a brief comment describing what they do.

with each nested block indented an additional four spaces. return -1. '********************************************************* Function intFindUser (strUserList(). The overview comments of a procedure should be indented one space. strTargetUser) Dim i Dim blnFound intFindUser = -1 i=0 ' Initialize loop counter ' Loop counter.Standard nested blocks should be indented four spaces. ' Returns: The index of the first occurrence of the strTargetUser ' ' in the strUserList array. The highest level statements that follow the overview comments should be indented four spaces. ‘Inputs: strUserList(): the list of users to be searched. ' strTargetUser: the name of the user to search for. ' Target found flag 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 VB Scripting 29 . For example: '********************************************************* ‘Purpose: Locates the first occurrence of a specified user ' In the User List array. If the target user is not found.

Loop End Function VB Scripting 30 .