VB Scripting
-
Upload
edwin-christopher -
Category
Documents
-
view
176 -
download
9
Transcript of VB Scripting
1. Introduction
VBScript stands for Visual Basic Script, a scripting language developed by Microsoft to be used with Microsoft products, mainly Internet Explorer.
2. 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 Description
Empty Variant is uninitialized. Value is 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.
VB Scripting 0
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.
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.
3. 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.
a. 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
b. Naming Restrictions:
VB Scripting 1
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.
c. 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 = 200
d. 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)
VB Scripting 2
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)
4. 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:
Const MyString = "This is my string."
Const 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. You represent Date literals and time literals by enclosing them in number signs (#). 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.
EXAMPLES
Constant Value DescriptionvbBlack &h00 Black
VbRed &hFF Red Date and Time Constants Defines date and time constants used by various date and time
functions.
VB Scripting 3
EXAMPLES
Constant Value DescriptionvbSunday 1 SundayvbMonday 2 Monday
Date Format Constants Defines constants used to format dates and times.
EXAMPLES
Constant Value Description
VbGeneralDate 0 Display a date and/or time. For real numbers, display a date and time. If there is no fractional part, display only a date. If there is no integer part, display time only. Date and time display is determined by your system settings.
VbLongDate 1 Display a date using the long date format specified in your computer's regional settings.
Miscellaneous Constants Defines constants that don't conveniently fit into any other category.
EXAMPLES
Constant Value DescriptionvbObjectError -2147221504 User-defined error numbers should be greater than
this value, for example, Err.Raise Number = vbObjectError + 1000
MsgBox Constants Defines constants used in the MsgBox function to describe button visibility, labeling, behavior, and return values.
EXAMPLES
Constant Value DescriptionvbOKOnly 0 Display OK button only.vbOKCancel 1 Display OK and Cancel buttons.vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons.
String Constants Defines a variety of non-printable characters used in string manipulation.
EXAMPLES
Constant Value Description
vbCr Chr(13) Carriage return.
VbCrLf Chr(13) & Chr(10)
Carriage return–linefeed combination.
vbFormFeed Chr(12) Form feed; not useful in Microsoft Windows.
Tristate Constants Defines constants used with functions that format numbers.
VB Scripting 4
EXAMPLES
Constant Value DescriptionvbUseDefault -2 Use default from computer's regional settings.vbTrue -1 TruevbFalse 0 False
VarType Constants Defines the various Variant subtypes.
EXAMPLES
Constant Value DescriptionvbEmpty 0 Uninitialized (default)vbNull 1 Contains no valid datavbInteger 2 Integer subtype
5. ERRORS:
There are two types of error
1. VBScript Run-time Errors2. 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. VBScript run-time errors occur while your script is being executed; when variable expressions are being evaluated, and memory is being dynamic allocated.
Error Number Description
429 ActiveX component can't create object
507 An exception occurred
449 Argument not optional
17 Can't perform requested operation
430 Class doesn't support Automation
506 Class not defined
11 Division by zero
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
VB Scripting 5
scripting language. VBScript syntax errors occur during the program compilation stage, before the program has begun to be executed.
Error Number Description1053 Class initialize or terminate do not have arguments1005 Expected '('1021 Expected 'Case'
1047 Expected 'Class'1014 Expected 'End'1015 Expected 'Function'1010 Expected identifier1012 Expected 'If'1019 Expected 'Loop'1020 Expected 'Next'
6. Operators:
Operators are used to "do operations" or manipulate variables and values.VBScript's many operators can be separated into four semi-distinct categories:
Math Operators Comparison Operators
Logic Operators
String Concatenation Operator
1. VBScript Operators: Math
When you want to perform addition, subtraction, multiplication, and other mathematical operations on numbers and variables use the operators listed below.
Operator English Example Result
+ Add 8+7 15
- Subtract 11-10 1
* Multiply 7*8 56
/ Divide 8/2 4
^ Exponent 2^4 16
Mod Modulus 15 Mod 10 5
VB Scripting 6
2. VBScript Operators: Comparison
When you want to compare two numbers to see which is bigger, if they're equal, or some other type of relationship use the comparison operators listed below. Common uses of comparison operators are within conditional statements like an If Statement or the condition check in a While Loop.
Operator English Example Result
= Equal To 10 =1 4 False
> Greater Than 10 > 14 False
< Less Than 10 < 14 True
>= Greater Than Or Equal To 10 >= 14 False
<= Less Than Or Equal To 10 <= 14 True
<> Not Equal To 10 <> 14 5
3. VBScript Operators: Logic
Logic operators are used to manipulate and create logical statements. For example if you wanted a variable shoeSize to be equal to 10 or 11 then you would do something like:
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, but we do have a list of the various logic operators available to you in VBScript.
VB Scripting 7
Operator English Example Result
Not Inverts Truth Value Not False True
Or Either Can Be True True Or False True
And Both Must Be True True And False False
4. VBScript String Concatenation Operator
When you have various strings that you would like to combine into one string use the concatenation operator. The concatenation operator acts as glue between the two or more strings you wish to attach, effectively making them into one string. String concatenation is often used when using the document. write function.
Operator English Example Result
& Connected To "Hello" & " there" "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.
7. Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In VBScript we have four conditional statements:
if statement
if...then...else statement
if...then...elseif statement
select case statement –
1. If statement
This statement is used to execute a set of code when a condition is true
VB Scripting 8
if i=10 Then msgbox "Hello"
There is no ..else.. in this syntax. You just tell the code to perform one action if the condition is true (in this case if i=10).
If you want to execute more than one statement when a condition is true, 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...then...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, and the other block will be executed otherwise (if i is not equal to 10).
3. if...then...elseif statement
This statement is used to select one of many sets of lines to execute
if payment="Cash" then
msgbox "You are going to pay cash!"
VB Scripting 9
elseif payment="Visa" then
msgbox "You are going to pay with visa."
elseif payment="AmEx" then
msgbox "You are going to pay with American Express."
else
msgbox "Unknown method of payment."
end If
8. 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), that is evaluated once. The value of the expression is then compared with the values for each Case in the structure. If there is a match, the block of code associated with that Case is executed.
9. Looping Statements:
VB Scripting 10
When we write code, we want the same block of code to run a number of times. We can use looping statements in our code to do this.
In VBScript we have four looping statements:
For...Next statement
For Each...Next statement
Do...Loop statement
1. For...Next Loop
It runs statements a specified number of times.
You can use a counter variable that increases or decreases with each repetition of the loop, like this:
For i=1 to 10
some code
Next
The For statement specifies the counter variable (i) and its start and end values. The Next statement increases the counter variable (i) by one.
Step Keyword
Using the Step keyword, you can increase or decrease the counter variable by the value you specify.
In the example below, the counter variable (i) is increased by two each time the loop repeats.
For i=2 To 10 Step 2
some code
Next
To decrease the counter variable, you must use a negative Step value. You must specify an end value that is less than the start value.
In the example below, the counter variable (i) is decreased by two each time the loop repeats.
VB Scripting 11
For i=10 To 2 Step -2
some code
Next
2. Exit a For...Next
You can exit a For...Next statement with the Exit For keyword.
3. For Each...Next Loop
It runs statements for each item in a collection or each element of an array
A For Each...Next loop repeats a block of code for each item in a collection, or for each element of an array.
dim cars(2)
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"
For Each x in cars
document.write(x & "<br />")
Next
4. Do...Loop
It loops while or until a condition is true
We can use Do...Loop statements to run a block of code when we do not know how many repetitions we want. The block of code is repeated while a condition is true or until a condition becomes true.
Repeating Code While a Condition is True
The While keyword is used to check a condition in a Do...Loop statement.
Do While i>10
VB Scripting 12
some code
Loop
If i equals 9, 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, even if i is less than 10.
Repeating Code Until a Condition Becomes True
The Until keyword is used to check a condition in a Do...Loop statement.
Do Until i=10
some code
Loop
If i equals 10, the code inside the loop will never be executed.
Do
some code
Loop Until i=10
The code inside this loop will be executed at least one time, even if i is equal to 10.
5. Exit a Do...Loop
we can exit a Do...Loop statement with the Exit Do keyword.
Do Until i=10
i=i-1
If i<10 Then Exit Do
Loop
VB Scripting 13
The code inside this loop will be executed as long as i is different from 10, and as long as i is greater than 10.
10.Procedures:
A Procedure is a unit of code outside of the main execution code. But it can be executed by
an invoking statement in the main execution code. There are 3 aspects about procedures:
1. Defining a procedure.
2. Invoking a procedure.
3. Exchanging data between the main execution code and a procedure.
VB offers two types of procedures:
1. Function Procedure - A procedure that returns a value explicitly.
2. Sub Procedure - A procedure that does not return any value explicitly.
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, "argument_list" a list of variables used to pass data into and/or out of the function, and "return_value" is the value to be returned explicitly to the invoking statements.
Of course, "argument_list" is optional.
Assigning the return value to the function name is also optional. If not given, default value will be returned to the invoking statements. But this is not recommended.
Invoking a function procedure is simple, no need of any special statements. Just use the function name with an argument list in any expression:
... function_name(argument_list) ...
This will cause the system to:
VB Scripting 14
Stop evaluating the expression.
Map data or variables based on the argument list.
Execute the entire statement block defined inside the function.
Take the value returned in the function name.
Continue to evaluate the expression.
If you want terminate a function procedure early, you can use the "Exit" statement:
Exit Function
Function Procedure Example
d = F2C(70.0)
document.writeln("Received Celsius = " & d)
d = F2C(212.0)
document.writeln("Received Celsius = " & d)
Function F2C(dFahrenheit)
document.writeln("")
document.writeln("Converting Fahrenheit = " & dFahrenheit)
dCelsius = (dFahrenheit - 32.0 ) / 1.8
document.writeln("Returning Celsius = " & dCelsius)
F2C = dCelsius
End Function
Here is the output:
Converting Fahrenheit = 70
Returning Celsius = 21.1111111111111
Received Celsius = 21.1111111111111
VB Scripting 15
Converting Fahrenheit = 212
Returning Celsius = 100
Received Celsius = 100
11.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), and "argument_list" a list of variables used to pass data into and/or out of the subroutine.
Of course, "argument_list" is optional.
Notice that subroutine does not return any values.
Invoking a subroutine is different than a function procedure. You can use one of the two syntaxes below:
1. Explicit call with "Call" statement:
Call sub_name(argument_list)
2. Explicit call with subroutine name:
sub_name argument_list
Both syntaxes will cause the system to:
Stop execution in main code flow.
Map data or variables based on the argument list.
Execute the entire statement block defined inside the subroutine.
Continue to execute main code flow.
If we want terminate a sub procedure early, you can use the "Exit" statement:
Exit Sub
VB Scripting 16
Sub Procedure Example
Call Hello("Tom")
Hello "Herong"
Sub Hello(sName)
document.writeln("")
document.writeln("Helo " & sName)
End Sub
Here is the output:
Helo Tom
Helo Herong.
Rules of Passing Arguments
As shown in previous examples, passing arguments to procedures seems to be a simple job. But it may cause confusion if you don't following the rules. VB script has the following rules on passing arguments to procedures:
1. By default, arguments are passed by reference. In this case, an argument name can be used as a variable that referring (sharing) the same data as the calling code.
2. But, arguments can be passed by value, if you put the key word "ByVal" before the argument name. In this case, an argument name can be used as a variable that contains a copy of the data provided by the calling code.
3. Of course, you put the word "ByRef" before an argument name to declare a pass-by-reference argument explicitly.
4. 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. This allows the procedure to output data back to the calling code.
5. A pass-by-value argument is safer than a pass-by-reference argument, because the procedure only gets a copy of the data. Any changes to that data will not affect the original data in the calling code.
6. Arrays can be passed by reference.
7. Arrays can also be passed by value. In this case, the procedure will get a copy of the array.
8. I don't know how to specify an array as the return value of a function procedure.
VB Scripting 17
Example - Passing Arguments by Reference
document.writeln("")
document.writeln("Test 1: Swapping two literals by reference")
document.writeln(" Before Sub: " & "Apple" & " | " & "Orange")
Call SwapByRef("Apple", "Orange")
document.writeln(" After Sub: " & "Apple" & " | " & "Orange")
vFirst = "Dog"
vSecond = "Cat"
document.writeln("")
document.writeln("Test 2: Swapping two variables by reference")
document.writeln(" Before Sub: " & vFirst & " | " & vSecond)
Call SwapByRef(vFirst, vSecond)
document.writeln(" After Sub: " & vFirst & " | " & vSecond)
Sub SwapByRef(ByRef vLeft, ByRef vRight)
vTemp = vLeft
vLeft = vRight
vRight = vTemp
document.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
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. By which we will not be able to receive the change done by the subroutine.
Test 2 shows that using variable for a "ByRef" argument lets to receive the change by the subroutine. After the subroutine call, values in vFirst and vSecond have been swapped.
"ByRef" keyword is optional.
Example - Passing Arguments by Value
document.writeln("")
document.writeln("Test 1: Swapping two literals by value")
document.writeln(" Before Sub: " & "Apple" & " | " & "Orange")
Call SwapByVal("Apple", "Orange")
document.writeln(" After Sub: " & "Apple" & " | " & "Orange")
vFirst = "Dog"
vSecond = "Cat"
document.writeln("")
document.writeln("Test 2: Swapping two variables by value")
document.writeln(" Before Sub: " & vFirst & " | " & vSecond)
Call SwapByVal(vFirst, vSecond)
document.writeln(" After Sub: " & vFirst & " | " & vSecond)
Sub SwapByVal(ByVal vLeft, ByVal vRight)
vTemp = vLeft
vLeft = vRight
VB Scripting 19
vRight = vTemp
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.
Test 2 shows that "ByVel" arguments will not bring any changes back to the calling code. After the subroutine call, values in vFirst and vSecond have not been changed at all.
12.Passing Array as Arguments
As I mentioned earlier, arrays can also be passed as arguments. If an array is passed by reference, the procedure is working on the same array as the calling code. If an array is passed by value, the procedure is working on a independent copy of the array in the calling code.
example code of using array as an argument
document.writeln("")
document.writeln("Test 1: Reversing a data literal")
bOk = ReverseArray("Apple")
aPets = Array("Bird", "Cat", "Dog", "Fish", "Rabbit")
document.writeln("")
VB Scripting 20
document.writeln("Test 2: Reversing an array")
document.writeln(" Before Sub: " & Join(aPets))
bOk = ReverseArray(aPets)
document.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.writeln("Error: You are not giving an array.")
ReverseArray = False
End If
End Function
Here is the output:
Test 1: Reversing a data literal
Error: You are not giving an array.
Test 2: Reversing an array
Before Sub: Bird Cat Dog Fish Rabbit
VB Scripting 21
After Sub: Rabbit Fish Dog Cat Bird
My "ReverseArray" function worked perfectly. You can take it a utility function to your application.
13. Variable Scope in Procedures
Variable Scope - The area of source code where a variable is accessible.
If you are not using procedures, variable scope is very simple. The scope of a variable is: from the statement where it is defined to the last statement of the code.
If you are using procedures, variable scope gets more complex. Here are some basic rules:
1. Global - If a variable is defined in the main code, its scope is from the statement where it is defined to the last statement of the entire code including all procedures.
2. Local - If a variable is defined in a procedure code, its scope is from the statement where it is defined to the last statement of the procedure.
3. Collision - If a variable is explicitly defined in a procedure code has the same name as a variable defined in the main code, the variable of the main code become in-accessible within this procedure.
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. You don't have to pass them as reference arguments to share them in a procedure.
The bad thing about rule #2 is that if you are using temporary variable in a procedure without explicit declaration, you could accidentally change the value of a global variable of the same name.
Rule #3 helps us to avoid the bad impact of rule #3, if you declare all temporary variables explicitly in procedures.
Example - Variable Scopes
Dim vGlobalDim
vGlobalDim = "Cat"
vGlobalNoDim = "Dog"
Dim vTempDim
vTempDim = "Bird"
VB Scripting 22
vTempNoDim = "Fish"
Call ScopeCheck()
document.writeln("")
document.writeln("Current value after Sub:")
document.writeln(" vGlobalDim = " & vGlobalDim)
document.writeln(" vGlobalNoDim = " & vGlobalNoDim)
document.writeln(" vLocalDim = " & vLocalDim)
document.writeln(" vLocalNoDim = " & vLocalNoDim)
document.writeln(" vTempDim = " & vTempDim)
document.writeln(" vTempNoDim = " & vTempNoDim)
Sub ScopeCheck()
Dim vLocalDim
vLocalDim = "Apple"
vLocalNoDim = "Orange"
Dim vTempDim
vTempDim = "Banana"
vTempNoDim = "Grape"
' Updating values
vGlobalDim = vGlobalDim & " - Updated by Sub"
vGlobalNoDim = vGlobalNoDim & " - Updated by Sub"
vLocalDim = vLocalDim & " - Updated by Sub"
vLocalNoDim = vLocalNoDim & " - Updated by Sub"
VB Scripting 23
vTempDim = vTempDim & " - Updated by Sub"
vTempNoDim = vTempNoDim & " - Updated by Sub"
' Showing values
document.writeln("")
document.writeln("Current value in Sub:")
document.writeln(" vGlobalDim = " & vGlobalDim)
document.writeln(" vGlobalNoDim = " & vGlobalNoDim)
document.writeln(" vLocalDim = " & vLocalDim)
document.writeln(" vLocalNoDim = " & vLocalNoDim)
document.writeln(" vTempDim = " & vTempDim)
document.writeln(" vTempNoDim = " & vTempNoDim)
End Sub
Here is the output:
Current value in Sub:
vGlobalDim = Cat - Updated by Sub
vGlobalNoDim = Dog - Updated by Sub
vLocalDim = Apple - Updated by Sub
vLocalNoDim = Orange - Updated by Sub
vTempDim = Banana - Updated by Sub
vTempNoDim = Grape - Updated by Sub
Current value after Sub:
vGlobalDim = Cat - Updated by Sub
vGlobalNoDim = Dog - Updated by Sub
VB Scripting 24
vLocalDim =
vLocalNoDim =
vTempDim = Bird
vTempNoDim = Grape - Updated by Sub
There are 6 variables in this example: vGlobalDim, vGlobalNoDim, vLocalDim, vLocalNoDim, vTempDim, and vTempNoDim.
The behavior of vGlobalDim and vGlobalNoDim is pretty consistent, defined in the main code; and accessible in the procedure. "Dim" or not makes no difference.
The behavior of vLocalDim and vLocalNoDim is also consistent, define in the procedure, not accessible in the main code. Notice that vLocalDim and vLocalNoDim are empty in the "after Sub" message.
The behavior of vTempDim and vTempNoDim shows that "Dim" statement forces vTempDim to a new local variable. So we have two variables of the same name, one in the main code, and one in the procedure. This is why vTempDim still has the old value after the subroutine call.
14.CODING CONVENTIONS:
Coding conventions are suggestions that may help you write code using Microsoft Visual Basic Scripting Edition. Coding conventions can include the following:
Naming conventions for objects, variables, 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.
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
VB Scripting 25
NEW_LINE
Variable 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
VB Scripting 26
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
VB Scripting 27
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.
VB Scripting 28
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.
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.
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 pseudo code 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.
VB Scripting 29
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 User List 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
VB Scripting 30
VB Scripting 31