• No results found

VB Scripting

N/A
N/A
Protected

Academic year: 2021

Share "VB Scripting"

Copied!
30
0
0

Loading.... (view fulltext now)

Full text

(1)

1.

1. In

Intr

trod

oduc

ucti

tion

on

VBScript stands for Visual Basic Script, a scripting language developed

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

used with Microsoft products, mainly Internet Explorer.

VBScript Data types:

VBScript Data types:

VBScript has only one data type called a Variant. A Variant is a special kind of data type 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 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

the only data type in VBScript, it is also the data type returned by all functions in VBScript.all functions in VBScript. At its simplest, a Variant can

At its simplest, a Variant can contain either numeric or string information. A Variantcontain either numeric or string information. A Variant behaves as a number when you

behaves as a number when you use it in a numeric context and as use it in a numeric context and as a string when you use it in aa string when you use it in a string context. That is, if you

string context. That is, if you are working with data that are working with data that looks like numbers, VBScript assumeslooks like numbers, VBScript assumes that it is numbers

that it is numbers and does what and does what is most appropriate for numbers. Similarly, if you're working withis 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 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 (" "

behave as strings by enclosing them in quotation marks (" " ).).

a.

a. Va

Vari

rian

ant S

t Sub

ubty

type

pes:

s:

The following table shows the subtypes of data that a Variant can contain. The following table shows the subtypes of data that a Variant can contain.

S

Suubbttyyppee DDeessccrriippttiioonn Emp

Emptyty VarVariaiant int is uns uniniinitiatializlized. ed. ValValue iue is 0 fs 0 for nor numeumeriric vac variariablebles or s or a zea zero- ro-length string ("") for string

length string ("") for string variables.variables. N

Nululll VVarariiaant nt iintntenentitiononalallly cy conontatainins s no no vvalalid id dadatta.a. B

Boooolleaeann CConontatainins eis eithther er TrueTrue or or FalseFalse.. B

Byyttee CCoonnttaaiinns s iinntteegger er iin tn thhe e rranange ge 0 t0 to o 252555.. In

Intetegegerr CoContntaiains ins intntegeger ier in thn the rae rangnge -3e -32,2,76768 to 38 to 32,2,76767.7. Curr

Currencyency -922,-922,337,2337,203,6803,685,4775,477.5808 to 9.5808 to 922,3322,337,203,7,203,685,4685,477.58077.5807.7. Lo

Longng CoContntaiains ns ininteteger ger in in ththe re ranange ge -2-2,1,14747,4,48383,6,648 48 to to 2,2,14147,7,483483,6,647.47. Sin

Singlegle ConContaitains ns a sa singingle-le-prepreciscisionion, f, floaloatinting-pg-poinoint t numnumber ber in in the the ranrangege -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 toto 3.402823E38 for positive values.

3.402823E38 for positive values. Dou

Doubleble ConContaitains a dns a doubouble-le-prepreciscisionion, fl, floatoatinging-po-point int numnumber iber in the n the ranrangege -1.79769313486232E308 to -4.94065645841247E-324 for negative -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for  values; 4.94065645841247E-324 to 1.79769313486232E308 for  positive values.

positive values. Date (

Date (TimeTime)) ContContains a nains a number tumber that rehat represenpresents a datts a date betwe between Janeen January 1, uary 1, 100 to100 to December 31, 9999.

(2)

St

Striringng CoContntaiains a vns a varariaiablble-e-lelengngth sth strtrining thg that cat can ban be up te up to appo approroxiximamatetely 2ly 2 billion characters in length.

billion characters in length. O

Obbjjeecctt CCoonnttaaiinns as an on obbjjeecctt.. E

Errrroorr CCoonnttaaiinns as an en errrroor nr nuummbbeerr.. You can use

You can use conversion functionsconversion functions to convert data from one subtype to another. In addition,to convert data from one subtype to another. In addition, the

the VarTypeVarType function returns information about how your data function returns information about how your data is stored within a Variant.is stored within a Variant.

Variable

Variable

A variable is a convenient placeholder that refers to a computer memory location 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. where you can store program information that may change during the time your script is running.

b.

b.

Declaring Variables:Declaring Variables:

You declare variables explicitly in your script

You declare variables explicitly in your script using theusing the DimDim statement. Thestatement. The PublicPublic statement,statement, and the

and the PrivatePrivate statement.statement. For example:

For example:

Dim DegreesFahrenheit Dim DegreesFahrenheit

You declare multiple variables by separating each

You declare multiple variables by separating each variable name with a comma.variable name with a comma. For example:

For example:

Dim Top, Bottom, Left, Right Dim Top, Bottom, Left, Right

c.

c.

Naming Restrictions:Naming Restrictions:

Variable names follow the standard rules for

Variable names follow the standard rules for naming anything in VBScript. A variablenaming anything in VBScript. A variable name:

name:

• Must begin with an Must begin with an alphabetic character.alphabetic character. •

• Cannot contain an embedded period.Cannot contain an embedded period. •

• Must not exceed 255 characters.Must not exceed 255 characters. •

• Must be unique in the scope in which Must be unique in the scope in which it is declared.it is declared.

d.

d.

Assigning Values to Variables:Assigning Values to Variables:

Values are assigned to variables creating an expression as follows: Values are assigned to variables creating an expression as follows: The variable is on the left side of the expression and

The variable is on the left side of the expression and the value you want to assign to thethe value you want to assign to the variable is on the right.

variable is on the right. For example: For example:

(3)

St

Striringng CoContntaiains a vns a varariaiablble-e-lelengngth sth strtrining thg that cat can ban be up te up to appo approroxiximamatetely 2ly 2 billion characters in length.

billion characters in length. O

Obbjjeecctt CCoonnttaaiinns as an on obbjjeecctt.. E

Errrroorr CCoonnttaaiinns as an en errrroor nr nuummbbeerr.. You can use

You can use conversion functionsconversion functions to convert data from one subtype to another. In addition,to convert data from one subtype to another. In addition, the

the VarTypeVarType function returns information about how your data function returns information about how your data is stored within a Variant.is stored within a Variant.

Variable

Variable

A variable is a convenient placeholder that refers to a computer memory location 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. where you can store program information that may change during the time your script is running.

b.

b.

Declaring Variables:Declaring Variables:

You declare variables explicitly in your script

You declare variables explicitly in your script using theusing the DimDim statement. Thestatement. The PublicPublic statement,statement, and the

and the PrivatePrivate statement.statement. For example:

For example:

Dim DegreesFahrenheit Dim DegreesFahrenheit

You declare multiple variables by separating each

You declare multiple variables by separating each variable name with a comma.variable name with a comma. For example:

For example:

Dim Top, Bottom, Left, Right Dim Top, Bottom, Left, Right

c.

c.

Naming Restrictions:Naming Restrictions:

Variable names follow the standard rules for

Variable names follow the standard rules for naming anything in VBScript. A variablenaming anything in VBScript. A variable name:

name:

• Must begin with an Must begin with an alphabetic character.alphabetic character. •

• Cannot contain an embedded period.Cannot contain an embedded period. •

• Must not exceed 255 characters.Must not exceed 255 characters. •

• Must be unique in the scope in which Must be unique in the scope in which it is declared.it is declared.

d.

d.

Assigning Values to Variables:Assigning Values to Variables:

Values are assigned to variables creating an expression as follows: Values are assigned to variables creating an expression as follows: The variable is on the left side of the expression and

The variable is on the left side of the expression and the value you want to assign to thethe value you want to assign to the variable is on the right.

variable is on the right. For example: For example:

(4)

B = 200 B = 200

e.

e.

Array Variables:Array Variables:

Sometimes you want to assign more than one value to a

Sometimes you want to assign more than one value to a single variable. Then you cansingle variable. Then you can create a variable that can contain a series of values. This is

create a variable that can contain a series of values. This is called an array variable. Thecalled an array variable. The declaration of an array variable uses parentheses ( ) following the variable name.

declaration of an array variable uses parentheses ( ) following the variable name. In the following example, an array

In the following example, an array containincontaining 3 g 3 elements is declared:elements is declared: Dim names(2)

Dim names(2)

The number shown in the parentheses is 2. We start at

The number shown in the parentheses is 2. We start at zero so this array contains 3zero so this array contains 3 elements. This is a fixed-size array.

elements. This is a fixed-size array. You assign data to each of the

You assign data to each of the elements of the array like this:elements of the array like this: names(0)="Tove" names(0)="Tove" names(1)="Jani" names(1)="Jani" names(2)="Stale" names(2)="Stale"

Similarly, the data can be retrieved from any element using the index of the particular array Similarly, the data can be retrieved from any element using the index of the particular array element you want.

element you want. Like this: Like this:

mother=names(0) mother=names(0) You can have up to 60

You can have up to 60 dimensions in an array. Multiple dimensions are declared bydimensions in an array. Multiple dimensions are declared by

separating the numbers in the parentheses with commas. Here we have a two-dimensional array separating the numbers in the parentheses with commas. Here we have a two-dimensional array consisting of 5 rows and 7 columns:

consisting of 5 rows and 7 columns: dim table(4, 6)

dim table(4, 6)

2.

2. CO

CONS

NSTA

TANT

NTS:

S:

A constant is a meaningful name that takes the place of a

A constant is a meaningful name that takes the place of a number or string and never number or string and never  changes.

changes.

VBScript defines a number of intrinsic constants VBScript defines a number of intrinsic constants

a.

a. CrCreateatining g CoConsnstatantntss

You create user-defined constants in VBScript using the

You create user-defined constants in VBScript using the Const statement; you can createConst statement; you can create string or numeric constants with meaningful names

string or numeric constants with meaningful names and assign them and assign them literal values.literal values. For example:

(5)

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 Description vbBlack &h00 Black

VbRed &hFF Red

• Date and Time Constants Defines date and time constants used by various date and time

functions. EXAMPLES

Constant Value Description vbSunday 1 Sunday

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

(6)

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 Description

vbObjectError -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 Description vbOKOnly 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.

EXAMPLES

Constant Value Description

vbUseDefault -2 Use default from computer's regional settings.

vbTrue -1 True

vbFalse 0 False

• VarType Constants Defines the various Variant subtypes.

(7)

Constant Value Description vbEmpty 0 Uninitialized (default)

vbNull 1 Contains no valid data vbInteger 2 Integer subtype

3. ERRORS:

There are two types of error  1. VBScript Run-time Errors 2. 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 scripting language. VBScript syntax errors occur during the program compilation stage, before the program has begun to be executed.

Error Number Description

1053 Class initialize or terminate do not have arguments 1005 Expected '(' 1021 Expected 'Case' 1047 Expected 'Class' 1014 Expected 'End' 1015 Expected 'Function' 1010 Expected identifier   1012 Expected 'If'

(8)

1019 Expected 'Loop' 1020 Expected 'Next'

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

= EqualTo 10=14 False

> Greater Than 10 > 14 False < LessThan 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:

(9)

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.

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.

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

(10)

• select case statement –

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

(11)

if payment="Cash" then

msgbox "You are going to pay cash!" 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 

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

(12)

7.

Looping Statements:

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.

(13)

In the example below, the counter variable (i) is decreased by two each time the loop repeats.

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

(14)

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

(15)

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.

8.

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 p rocedure 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:

(16)

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

(17)

Converting Fahrenheit = 212 Returning Celsius = 100 Received Celsius = 100

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

(18)

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.

(19)

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

(20)

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

(21)

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.

10.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("")

(22)

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

(23)

After Sub: Rabbit Fish Dog Cat Bird

My "ReverseArray" function worked perfectly. You can take it a utility function to your  application.

11. 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"

(24)

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"

(25)

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

(26)

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.

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

(27)

Variable Naming Conventions

For purposes of readability and consistency, use the prefixes listed in the following table, along with descriptive names for va riables in your VBScript code.

Subtype Prefix Example

Boolean bln blnFound

Byte byt bytRasterData

Date (Time) dtm dtmStart

Double dbl dblTolerance

Error err errOrderNum

Integer int intQuantity

Long lng lngDistance

Object obj objCurrent

Single sng sngAverage

String str strFirstName

Variable Scope

Variables should always be defined with the smallest scope possible. VBScript variables can have the following scope.

Scope Where Variable Is Declared Visibility

Procedure-level

Event, Function, or Sub procedure

Visible in the procedure in which it is declared.

Script-level HEAD section of an HTML page, outside any procedure

Visible in every procedure in the script.

Variable Scope Prefixes

As script size grows, so does the value of being able to quickly differentiate the scope of  variables. A one-letter scope prefix preceding the type prefix provides this, without unduly increasing the size of variable names.

Scope Prefix Example

(28)

Script-level s sblnCalcInProgress

Descriptive Variable and Procedure Names

The body of a variable or procedure name should u se 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 d ifficult 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

3DPanel pnl pnlGroup

Animated button ani aniMailBox

Check box chk chkReadOnly

Combo box, drop-down list box cbo cboEnglish

Command button cmd cmdExit

Common dialog dlg dlgFileOpen

Frame fra fraLanguage

Horizontal scroll bar hsb hsbVolume

Image img imgIcon

Label lbl lblHelpMessage

Line lin linVertical

List Box lst lstPolicyCodes

Spin spn spnPages

Textbox txt txtLastName

(29)

Slider sld sldScale

Code Commenting Conventions

All procedures should begin with a brief comment describing what they do. This description should not describe the implementation details (how it does it) because these often change over  time, resulting in unnecessary comment maintenance work, or worse yet, erroneous comments. The code itself and any necessary inline comments describe the implementation.

Arguments passed to a procedure should be described when their purpose is not obvious and when the procedure expects the arguments to be in a specific range. Function return values and other variables that are changed by the procedure, especially through reference arguments, should also be described at the beginning of each procedure.

Procedure header comments should include the following section headings. For examples, see the section "Formatting Your Code" that follows.

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:

(30)

Standard nested blocks should be indented four spaces.

The overview comments of a procedure should be indented one space.

The highest level statements that follow the overview comments should be indented four  spaces, with each nested block indented an additional four spaces. For example:

'*********************************************************

‘Purpose: Locates the first occurrence of a specified user  ' In the 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 

References

Related documents

Composing a TOSCA Service Template for a “SugarCRM” Application using Vnomic’s Service Designer, www.vnomic.com. The SugarCRM application include

 Enable / Disable or Show / Hide: AutoPlay, Play Random, Text BG Shadow, Repeat Images, Buttons -.. Next/Prev/Play/Pause/Timer/Change Image, FrontImage - Shadow, Border,

105(2)(a) again claiming show Defendant has sufficient contacts with Maryland to be sued in Maryland. Plaintiff also reminds the Court that the Court must construe all allegations

This guide is about how to create real income streams based on real value that comes from your very real business, whether you're a blogger, freelancer, professional service

You finally expand this out a pool by declaring a string variable In C strings are stored as key character pointers or const char const char theStringYo.. String Pointers in

Creditors who assert that the debtors are not entitled to a discharge of any debts or who want to have a particular debt excepted from discharge may be required to file a complaint

As Vintura excels in both stakeholder management and in developing concepts for complex problems, this project allowed us to work in our sweet spot. From the very beginning,

Ideal Logic HIUs incorporate one or two plate heat exchangers to transfer heat from a central boiler plant to individual heating and hot water systems within apartments. Ideal