• No results found

Advanced+QTP+Open+Order

N/A
N/A
Protected

Academic year: 2021

Share "Advanced+QTP+Open+Order"

Copied!
43
0
0

Loading.... (view fulltext now)

Full text

(1)

VBScript Tutorial

VBScript Tutorial

(For QTP)

(For QTP)

1)

1) InIntrtrododucuctitionon 2

2)) CCoommmmeennttss 3)

3) VB SVB Scrcripipt Vart Variaiablbleses 4)

4) VB SVB Scrcripipt Dat Data Tta Typypeses 5)

5) VB SVB Scrcripipt Opt Opereratatororss 6)

6) InpInput/ut/OutOutput put OpeOperatrationionss 7)

7) CCononsstatanntsts 8)

8) ConConditditionional al StaStatemtemententss 9)

9) GeGeneneraral El Exaxampmpleless 10)Loop Through Code 10)Loop Through Code 11)Procedures

11)Procedures

12)Built-In Functions 12)Built-In Functions

13)VBScript syntax rules and guidelines 13)VBScript syntax rules and guidelines 14)Errors

14)Errors

15)File System Operations 15)File System Operations 16)Test Requirements 16)Test Requirements 17) Solutions 17) Solutions 18)QTP Add-Ins Information 18)QTP Add-Ins Information 19) VBScript Glossary 19) VBScript Glossary

(2)

Introduction

Introduction

o

o VBScript is a scripting language.VBScript is a scripting language. o

o A scripting language is a A scripting language is a lightweight programming language.lightweight programming language. o

o VBScript is a light version of VBScript is a light version of Microsoft's programming language Visual Basic.Microsoft's programming language Visual Basic.

When a VBScript is inserted into

When a VBScript is inserted into a HTML document, the Internet browser will a HTML document, the Internet browser will readread the HTML and interpret the

the HTML and interpret the VBScript. The VBScript can be executed immediately, orVBScript. The VBScript can be executed immediately, or at a later event.

at a later event.

Microsoft Visual Basic Scripting Edition brings active scripting to

Microsoft Visual Basic Scripting Edition brings active scripting to a wide variety of a wide variety of  environments, including Web client scripting in Microsoft Internet Explorer and environments, including Web client scripting in Microsoft Internet Explorer and WebWeb server scripting in Microsoft Internet Information Service.

server scripting in Microsoft Internet Information Service. 1.1 Windows Script Host (WSH)

1.1 Windows Script Host (WSH) It is a

It is a Windows administration tool. WSH creates an environment for hosting Windows administration tool. WSH creates an environment for hosting scripts.scripts. That is, when a script arrives at your computer, WSH plays the part of the host — it That is, when a script arrives at your computer, WSH plays the part of the host — it makes objects and services available for the script and provides a set of guidelines makes objects and services available for the script and provides a set of guidelines within which the script is executed. Among other

within which the script is executed. Among other things, Windows Script Hostthings, Windows Script Host manages security and invokes the appropriate script

manages security and invokes the appropriate script engineengine Windows Script Host is built into

Windows Script Host is built into Microsoft Windows 98, 2000, and MillenniumMicrosoft Windows 98, 2000, and Millennium Editions and higher versions.

Editions and higher versions.

A Windows script is a text file. We can create a script with any text editor as

A Windows script is a text file. We can create a script with any text editor as long aslong as we save our script with a

we save our script with a WSH-compatible script extension (.js, vbs, or .wsf).WSH-compatible script extension (.js, vbs, or .wsf). The most commonly available text editor is already installed on our computer — The most commonly available text editor is already installed on our computer — Notepad. We can also

Notepad. We can also use your favorite HTML editor, VbsEdit, Microsoft Visual C++,use your favorite HTML editor, VbsEdit, Microsoft Visual C++, or Visual InterDev.

or Visual InterDev.

1.2 Creating a script with Notepad 1.2 Creating a script with Notepad 1.Start Notepad.

1.Start Notepad.

2.Write your script. For example purposes, type Msgbox "Hello

2.Write your script. For example purposes, type Msgbox "Hello VB Script"VB Script"

3.Save this text file with a .vbs extension (instead of the default .txt extension). For 3.Save this text file with a .vbs extension (instead of the default .txt extension). For example, Hello.vbs

example, Hello.vbs

4.Navigate to the file you just saved, and double-click it. 4.Navigate to the file you just saved, and double-click it. 5.Windows Script Host invokes the VB Script engine and

5.Windows Script Host invokes the VB Script engine and runs your script. In theruns your script. In the example, a message box is displayed with the message "Hello VB Script"

example, a message box is displayed with the message "Hello VB Script" 1.3 Hosting Environments and

1.3 Hosting Environments and Script EnginesScript Engines

Scripts are often embedded in Web pages, either in an HTML page (on the client Scripts are often embedded in Web pages, either in an HTML page (on the client side) or in an ASP page (on the server side).

(3)

In the case of a script embedded in an HTML page, the

In the case of a script embedded in an HTML page, the engine component thatengine component that interprets and runs the script code is

interprets and runs the script code is loaded by the Web loaded by the Web browser, such as Internetbrowser, such as Internet Explorer.

Explorer.

In the case of a script embedded in an ASP page, the engine that

In the case of a script embedded in an ASP page, the engine that interprets and runsinterprets and runs the script code is built

the script code is built into Internet Information Services (IIS).into Internet Information Services (IIS). Windows Script Host executes scripts that exist outside an

Windows Script Host executes scripts that exist outside an HTML or ASP page andHTML or ASP page and that stand on their own as text files.

that stand on their own as text files. 1.4 Available Script Engines 1.4 Available Script Engines Generally, we write scripts in either

Generally, we write scripts in either Microsoft JScript or VBScript, the two scriptMicrosoft JScript or VBScript, the two script engines that ship with Microsoft Windows 98,

engines that ship with Microsoft Windows 98, 2000 and Millennium Editions.2000 and Millennium Editions. We can use other script

We can use other script engines, such as Perl, REXX, and Python, with Windowsengines, such as Perl, REXX, and Python, with Windows Script Host.

Script Host.

A stand-alone script written in JScript has

A stand-alone script written in JScript has the .js extension; a stand-alone scriptthe .js extension; a stand-alone script written in VBScript has the .vbs extension. These

written in VBScript has the .vbs extension. These extensions are registered withextensions are registered with Windows. When we run one of

Windows. When we run one of these types of files, Windows starts Windows Scriptthese types of files, Windows starts Windows Script Host, which invokes the associated script engine to

(4)

Comments

Comments

The comment argument is the text of any comment we want to include. The comment argument is the text of any comment we want to include. 2.0 Purpose of comments:

2.0 Purpose of comments:

o

o We can use comments for making the We can use comments for making the script understandable.script understandable. o

o We can use comments for making one We can use comments for making one or more statements disable fromor more statements disable from

execution. execution. 2.1 Syntax

2.1 Syntax Rem

Rem comment comment (After the Rem keyword, a space (After the Rem keyword, a space is required before comment.)is required before comment.)

Or Or Apostrophe (') symbol before the comment Apostrophe (') symbol before the comment

2.2 Comment/Uncomment a block of statements 2.2 Comment/Uncomment a block of statements Select block of statement and

Select block of statement and use short cut key Ctrl + use short cut key Ctrl + M (for comment)M (for comment) Select comment block and use short cut key

Select comment block and use short cut key Ctrl + Shift + M Ctrl + Shift + M (for uncomment)(for uncomment) 2.3 Example

(5)

VB Script Variables

VB Script Variables

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 we can store program information that

where we can store program information that may change during the time may change during the time our scriptour script is running.

is running.

3.1 Declaring Variables 3.1 Declaring Variables

We declare variables explicitly in our script using the Dim statement, the Public We declare variables explicitly in our script using the Dim statement, the Public statement, and the Private statement.

statement, and the Private statement. For example: For example: Dim city Dim city Dim x Dim x

We declare multiple variables by separating each variable name with a comma. For We declare multiple variables by separating each variable name with a comma. For Example:

Example:

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

We can also declare a variable implicitly by simply using its name

We can also declare a variable implicitly by simply using its name in our script. Thatin our script. That is not generally a good practice because we could misspell the variable name in one is not generally a good practice because we could misspell the variable name in one or more places, causing unexpected results when our script is

or more places, causing unexpected results when our script is run. For that reason,run. For that reason, the Option Explicit statement is available to require explicit declaration of all

the Option Explicit statement is available to require explicit declaration of all variables.

variables.

The Option Explicit statement should be

The Option Explicit statement should be the first statement in our script.the first statement in our script. 3.2 Option Explicit

3.2 Option Explicit

Forces explicit declaration of all variables in a script. Forces explicit declaration of all variables in a script. Option

Option Explicit Explicit ' ' Force Force explicit explicit variable variable declaration.declaration. Dim

Dim MyVar MyVar ' ' Declare Declare variable.variable. MyInt

MyInt = = 10 10 ' ' Undeclared Undeclared variable variable generates generates error.error. MyVar =

MyVar = 10 10 ' Decl' Declared variable ared variable does does not genenot generate errorrate error.. 3.3 Naming Restrictions for Variables

3.3 Naming Restrictions for Variables Variable names follow the

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

name:

o

o Must begin with an alphabetic character.Must begin with an alphabetic character. o

o Cannot contain an embedded period.Cannot contain an embedded period. o

o Must not exceed 255 characters.Must not exceed 255 characters. o

(6)

3.4 Scope of Variables 3.4 Scope of Variables

A variable's scope is determined by

A variable's scope is determined by where we declare it.where we declare it.

When we declare a variable within a procedure, only code within that procedure can When we declare a variable within a procedure, only code within that procedure can access or change the value of that variable.

access or change the value of that variable.

If we declare a variable outside a procedure, we make it recognizable to all If we declare a variable outside a procedure, we make it recognizable to all thethe procedures in our script. This is a

procedures in our script. This is a script-level variable, and it has script-level variable, and it has script-level scope.script-level scope. 3.5 Life Time of Variables

3.5 Life Time of Variables

The lifetime of a variable depends on how long it exists. The lifetime of a variable depends on how long it exists.

The lifetime of a script-level variable extends from the time it is declared until the The lifetime of a script-level variable extends from the time it is declared until the time the script is finished

time the script is finished running.running.

At procedure level, a variable exists only as long as you are in the procedure. At procedure level, a variable exists only as long as you are in the procedure. 3.6 Assigning Values to Variables

3.6 Assigning Values to Variables Values are assigned to variables

Values are assigned to variables creating an expression as follows:creating an expression as follows:

The variable is on the left side of the expression and the value you want to a

The variable is on the left side of the expression and the value you want to a ssign tossign to the variable is on the right.

the variable is on the right. For example: For example: A = 200 A = 200 City = “Hyderabad”  City = “Hyderabad”  X=100: Y=200 X=100: Y=200

3.7 Scalar Variables and Array

3.7 Scalar Variables and Array VariablesVariables

A variable containing a single value is a scalar variable. A variable containing a single value is a scalar variable.

A variable containing a series of values, is called an array variable. A variable containing a series of values, is called an array variable.

Array variables and scalar variables are declared in the same way, except that the Array variables and scalar variables are declared in the same way, except that the declaration of an array variable uses parentheses () following the variable name. declaration of an array variable uses parentheses () following the variable name. Example:

Example: Dim A(3) Dim A(3)

Although the number shown in the parentheses is

Although the number shown in the parentheses is 3, all arrays in 3, all arrays in VBScript are zero-VBScript are zero-based, so this array actually

based, so this array actually contains 4 elements.contains 4 elements.

We assign data to each of the elements of the array using an index

We assign data to each of the elements of the array using an index into the array.into the array. Beginning at zero and ending at 4, data can

Beginning at zero and ending at 4, data can be assigned to the elements of an arraybe assigned to the elements of an array as follows:

(7)

A(0) = 256 A(0) = 256 A(1) = 324 A(1) = 324 A(2) = 100 A(2) = 100 A(3) = 55 A(3) = 55

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

particular array element you want. For example:

For example:

SomeVariable = A(4) SomeVariable = A(4)

Arrays aren't limited to a single dimension. We can have as many as 60 dimensions, Arrays aren't limited to a single dimension. We can have as many as 60 dimensions, although most people can't comprehend more than

although most people can't comprehend more than three or four dimensions.three or four dimensions.

In the following example, the MyTable variable is a two-dimensional array consisting In the following example, the MyTable variable is a two-dimensional array consisting of 6 rows and 11

of 6 rows and 11 columns:columns: Dim MyTable(5, 10)

Dim MyTable(5, 10)

In a two-dimensional array, the

In a two-dimensional array, the first number is always the number of first number is always the number of rows; therows; the second number is the number of

second number is the number of columns.columns. 3.8 Dynamic Arrays

3.8 Dynamic Arrays

We can also declare an array whose size changes during the time our script is We can also declare an array whose size changes during the time our script is running. This is called a dynamic array.

running. This is called a dynamic array.

The array is initially declared within a procedure using either the Dim statement or The array is initially declared within a procedure using either the Dim statement or using the ReDim statement.

using the ReDim statement.

However, for a dynamic array, no

However, for a dynamic array, no size or number of dimensions is placed size or number of dimensions is placed inside theinside the parentheses. parentheses. For example: For example: Dim MyArray() Dim MyArray() ReDim AnotherArray() ReDim AnotherArray() To use a dynamic a

To use a dynamic array, you must subsequently use ReDim to determine the rray, you must subsequently use ReDim to determine the numbernumber of dimensions and the size

of dimensions and the size of each dimension.of each dimension.

In the following example, ReDim sets the initial size of the dynamic array to

In the following example, ReDim sets the initial size of the dynamic array to 25. A25. A subsequent ReDim statement resizes the array to

subsequent ReDim statement resizes the array to 30, but uses the Preserve keyword30, but uses the Preserve keyword to preserve the contents of the array as the resizing takes place.

to preserve the contents of the array as the resizing takes place. ReDim MyArray(25)

ReDim MyArray(25)

ReDim Preserve MyArray(30) ReDim Preserve MyArray(30)

There is no limit to the number of times we can resize a dynamic array, although if  There is no limit to the number of times we can resize a dynamic array, although if  we make an array smaller, we lose the data in the eliminated elements.

(8)

VB Script Data Types

VB Script Data Types

VBScript has only one data type called a Variant. A Variant is a special kind

VBScript has only one data type called a Variant. A Variant is a special kind of dataof data type that can contain different kinds of information, depending on how it is used. 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

Because Variant is the only data type in VBScript, it is also the data type returned bytype returned by all functions in VBScript.

all functions in VBScript. 4.1 Variant Subtypes 4.1 Variant Subtypes

Beyond the simple numeric or string classifications, a

Beyond the simple numeric or string classifications, a Variant can make furtherVariant can make further distinctions about the specific nature of

distinctions about the specific nature of numeric information. For example, we cannumeric information. For example, we can have numeric information that represents a date or a time. When used with other have numeric information that represents a date or a time. When used with other date or time data, the result is always expressed as a date or a time. We can also date or time data, the result is always expressed as a date or a time. We can also have a rich variety of numeric information ranging in size from Boolean values to have a rich variety of numeric information ranging in size from Boolean values to huge floating-point numbers. These different categories of information that

huge floating-point numbers. These different categories of information that can becan be contained in a Variant are called subtypes. Most of the time, we can just put the kind contained in a Variant are called subtypes. Most of the time, we can just put the kind of data we want in a Variant, and the

of data we want in a Variant, and the Variant behaves in a way that is mostVariant behaves in a way that is most appropriate for the data it contains.

appropriate for the data it contains.

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

Suubbttyyppee DDeessccrriippttiioonn Empty

Empty Variant is uninitialized. VVariant is uninitialized. Value is 0 for nalue is 0 for numeric variables or umeric variables or a zero-length sa zero-length stringtring ("") for string variables.

("") for string variables. Nu

Nullll VaVaririanant int intetentntioionanally clly conontatainins no vs no valalid did datata.a. B

Boooolleeaann CCoonnttaaiinns s eeiitthheer r TTrruue e oor r FFaallssee.. By

Bytete CoContntainains ins intetegeger in tr in the rhe ranange 0 ge 0 to 2to 25555.. In

Inteteggerer CoConntatainins s inintetegeger r iin n ththe e rranange ge -3-32,2,7768 68 to to 3232,7,76767.. Cu

Currrrenencycy -9-922,22,33337,7,20203,3,68685,5,47477.7.585808 08 to to 92922,2,33337,7,20203,3,685685,4,47777.5.580807.7. Long

Long ContContains ains integinteger in er in the the range range -2,14-2,147,483,7,483,648 t648 to 2,o 2,147,4147,483,6483,647.7. Single

Single Contains a Contains a single-precision, single-precision, floating-point number floating-point number in the in the range -3.402823Erange -3.402823E3838 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for

to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positivepositive values.

values. Double

DoubleContains a double-precision, floating-point number in the rangeContains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative

-1.79769313486232E308 to -4.94065645841247E-324 for negative values;values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. 4.94065645841247E-324 to 1.79769313486232E308 for positive values. Date (T

Date (Time)ime) ContaContains a nins a number umber that rthat represepresents a dents a date betwate between Jaeen January nuary 1, 100 1, 100 toto December 31, 9999.

December 31, 9999. String

String Contains a Contains a variable-length svariable-length string that tring that can be can be up to up to approximately 2 approximately 2 billionbillion characters in length.

characters in length. Objec

Objectt ContContains an obains an objectject.. Er

Errororr CoContntainains an es an errrror nor numumbeber.r.

We can use conversion functions to convert data

We can use conversion functions to convert data from one subtype to another. Infrom one subtype to another. In addition, the VarType function returns information about how your

addition, the VarType function returns information about how your data is storeddata is stored within a Variant.

(9)

VB Script Operators

VB Script Operators

Operators are used for performing mathematical, comparison and

Operators are used for performing mathematical, comparison and logical operations.logical operations. VBScript has a full range

VBScript has a full range of operators, including arithmetic operators, comparisonof operators, including arithmetic operators, comparison operators, concatenation operators, and logical operators.

operators, concatenation operators, and logical operators. 4.1 Operator Precedence

4.1 Operator Precedence

When several operations occur in an

When several operations occur in an expression, each part is evaluated and expression, each part is evaluated and resolvedresolved in a predetermined order called

in a predetermined order called operator precedence.operator precedence. We can use parentheses to override the

We can use parentheses to override the order of precedence and force some parts of order of precedence and force some parts of  an expression to be evaluated

an expression to be evaluated before others.before others.

Operations within parentheses are always performed before those outside.

Operations within parentheses are always performed before those outside. WithinWithin parentheses, however, standard operator precedence is maintained.

parentheses, however, standard operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated

operators are evaluated first, comparison operators are evaluated next, and logicalnext, and logical operators are evaluated last.

operators are evaluated last.

Comparison operators all have equal precedence; that is, they are evaluated in the Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear.

left-to-right order in which they appear. Arithmetic and logical operators are

Arithmetic and logical operators are evaluated in the following order of evaluated in the following order of precedence.precedence. 4.2 Arithmetic Operators:

4.2 Arithmetic Operators: O

Oppeerraattoorr DDeessccrriippttiioonn 1) E

1) Expoxponennentiatiatiotion Open Operatrator (or (^)^) Raises Raises a nua numbember to tr to the phe poweower of ar of an expn expononentent 2)

2) MuMultltipiplilicacatition on OpOpereratator or (*(*)) MuMultltipiplilies es twtwo o nunumbmberers.s. 3

3) D) Diivviissiioon On Oppeerraattoor (r (//)) DDiivviiddees ts twwo no nuummbbeerrs as annd rd reettuurrnns a s a ffllooaattiinngg--ppooiinntt result.

result. 4) In

4) Integteger Dier Divisvision Opion Operaerator (tor (\)\) DivDivideides two ns two numbumbers aners and retd returnurns an ins an integteger reser resultult.. 5

5) ) MMood d OOppeerraattoorr DDiivviiddees s ttwwo o nnuummbbeerrs s aannd d rreettuurrnns s oonnlly y tthhe e rreemmaaiinnddeerr.. 6

6) ) AAddddiittiioon n OOppeerraattoor r ((++)) SSuumms s ttwwo o nnuummbbeerrss.. 7)

7) SuSubtbtraractctioion On Opeperaratotor (r (-)-) FiFindnds ts the he didiffffererenence ce bebetwtweeeen tn two wo nunumbmberers os or ir indndicicatateses the negative value of

the negative value of a numeric expression.a numeric expression. 8)

8) ConConcatcatenaenation tion OpeOperatrator or (&)(&) ForForceces sts strinring cog concancatentenatiation oon of tf two wo expexpresressiosions.ns. 4.3 Comparison Operators

4.3 Comparison Operators Used to compare expressions. Used to compare expressions. Operator

Operator DescriptionDescription

1

1) ) == ((EEqquuaal l ttoo)) UUsseed d tto o ccoommppaarre e eexxpprreessssiioonnss.. 2

2) ) <<>> ((NNoot t eeqquuaal l ttoo)) UUsseed d tto o ccoommppaarre e eexxpprreessssiioonnss.. 3

3) ) << LLeesss s tthhaann 4

4) ) >> GGrraatteer r tthhaann 5) <=

(10)

6) >

6) >== GreateGreater thr than or an or equal equal toto 7

7) ) IIss OObbjjeecct t eeqquuiivvaalleennccee

4.4 Concatenation Operators 4.4 Concatenation Operators O

Oppeerraattoorr DDeessccrriippttiioonn 1) Addition Operator

1) Addition Operator (+)(+) Sums two numbersSums two numbers I

Iff TThheenn

1

1) ) BBootth h eexxpprreessssiioonns s aarre e nnuummeerriicc AAdddd.. 2

2) ) BBootth h eexxpprreessssiioonns s aarre e ssttrriinnggss CoConnccaatteennaattee.. 3) One expression is numeric and the

3) One expression is numeric and the other is a string other is a string

Add.

Add.

2) Concatenation 2) Concatenation Operator

Operator (&)(&)

Forces string concatenation of two

Forces string concatenation of two expressions.expressions.

4.5 Logical Operators 4.5 Logical Operators O

Oppeerraattoorr DDeessccrriippttiioonn SSyynnttaaxx 1

1) ) NNoott PPeerrffoorrmms s llooggiiccaal l nneeggaattiioon n oon n aann expression

expression

result= Not expression result= Not expression 2

2) ) AAnndd PPeerrffoorrmms s a a llooggiiccaal l ccoonnjjuunnccttiioon n oon n ttwwoo expressions.

expressions.

result= expression1 And result= expression1 And expression2

expression2 3

3) ) OOrr PPeerrffoorrmms s a a llooggiiccaal l ddiissjjuunnccttiioon n oon n ttwwoo expressions. expressions. result= expression1 Or result= expression1 Or expression2 expression2 4

4) ) XXoorr PPeerrffoorrmms s a a llooggiiccaal l eexxcclluussiioon n oon n ttwwoo expressions.

expressions.

result= expression1 Xor result= expression1 Xor expression2

expression2 5

5) ) EEqqvv PPeerrffoorrmms s a a llooggiiccaal l eeqquuiivvaalleenncce e oonn two expressions.

two expressions.

result= expression1 Eqv result= expression1 Eqv expression2

expression2 6

6) ) IImmpp PPeerrffoorrmms s a a llooggiiccaal l iimmpplliiccaattiioon n oon n ttwwoo expressions.

expressions.

result= expression1 Imp result= expression1 Imp expression2

(11)

Input/Output Operations

Input/Output Operations

6.1 InputBox Function

6.1 InputBox Function

Displays a prompt in a dialog box, waits for the user to input text or click a button, Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box.

and returns the contents of the text box. Example:

Example: Dim Input Dim Input

Input = InputBox("Enter your name") Input = InputBox("Enter your name") MsgBox ("You entered: " & Input) MsgBox ("You entered: " & Input) 6.2 MsgBox Function

6.2 MsgBox Function

Displays a message in a dialog box, waits for the user to click a button, and returns a Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the

value indicating which button the user clicked.user clicked. Example:

Example: Dim MyVar Dim MyVar

MyVar = MsgBox ("Hello World!", 65,

MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")"MsgBox Example") ' MyVar contains either 1 or

(12)

VB Script Constants

VB Script Constants

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 andnumber or string and never changes.

never changes.

7.1 Creating Constants 7.1 Creating Constants

We create user-defined constants in VBScript using the Const statement.

We create user-defined constants in VBScript using the Const statement. Using theUsing the Const statement, we can create string or

Const statement, we can create string or numeric constants with meaningful namesnumeric constants with meaningful names and assign them literal values.

and assign them literal values. Const statement

Const statement

Declares constants for use in place of literal values. Declares constants for use in place of literal values. Example:

Example:

Const MyString = "This is my string." Const MyString = "This is my string." Const MyAge = 49

Const MyAge = 49

Const CutoffDate = #6-1-97# Const CutoffDate = #6-1-97#

Note that String literal is enclosed in quotation marks (" "). Note that String literal is enclosed in quotation marks (" ").

Represent Date literals and time literals by enclosing them in number signs (#). Represent Date literals and time literals by enclosing them in number signs (#). We declare multiple constants by separating each constant name and value with a We declare multiple constants by separating each constant name and value with a comma. For example:

comma. For example:

Const price= 100, city= “Hyderabad”, x= 27 Const price= 100, city= “Hyderabad”, x= 27

(13)

Conditional Statements

Conditional Statements

We can control the flow

We can control the flow of our script with conditional statements and of our script with conditional statements and loopinglooping statements.

statements.

Using conditional statements, we can write

Using conditional statements, we can write VBScript code that makes decisions andVBScript code that makes decisions and repeats actions. The following conditional statements are

repeats actions. The following conditional statements are available in VBScript:available in VBScript:

1) If…Then…Else Statement

1) If…Then…Else Statement

2) Select Case Statement

2) Select Case Statement

8.1 Making Decisions Using If...Then...Else

8.1 Making Decisions Using If...Then...Else

The If...Then...Else statement is used to evaluate

The If...Then...Else statement is used to evaluate whether a condition is True orwhether a condition is True or False and, depending on the result, to specify one or more statements to run. False and, depending on the result, to specify one or more statements to run. Usually the condition is an

Usually the condition is an expression that uses a comparison operator to compareexpression that uses a comparison operator to compare one value or variable with another.

one value or variable with another.

If...Then...Else statements can be nested to as

If...Then...Else statements can be nested to as many levels as you need.many levels as you need. 8.1.1 Running a Statement if a

8.1.1 Running a Statement if a Condition is True (single statement)Condition is True (single statement) To run only one statement

To run only one statement when a condition is True, use the when a condition is True, use the single-line syntax forsingle-line syntax for the If...Then...Else statement.

the If...Then...Else statement. Dim myDate

Dim myDate

myDate = #2/13/98# myDate = #2/13/98#

If myDate < Now Then myDate = Now If myDate < Now Then myDate = Now

8.1.2 Running Statements if a Condition is

8.1.2 Running Statements if a Condition is True (multiple statements)True (multiple statements) To run more than one line

To run more than one line of code, we must use the of code, we must use the multiple-line (or block) syntax.multiple-line (or block) syntax. This syntax includes the End If

This syntax includes the End If statement.statement. Dim x Dim x x= 20 x= 20 If If x>10 x>10 ThenThen

msgbox "Hello Tester" msgbox "Hello Tester" msgbox "x value is: "&x msgbox "x value is: "&x msgbox "Bye Bye"

msgbox "Bye Bye" End If 

End If 

8.1.3 Running Certain Statements if a Condition is

8.1.3 Running Certain Statements if a Condition is True and Running OthersTrue and Running Others if a Condition is False

if a Condition is False We can use an

We can use an If...Then...Else statement to define two blocks of executableIf...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the statements: one block to run if the condition is True, the other block to run if the condition is False.

condition is False. Example:

(14)

Dim x Dim x

x= Inputbox (" Enter a value") x= Inputbox (" Enter a value") If

If x>100 x>100 ThenThen

Msgbox "Hello Tester" Msgbox "Hello Tester"

Msgbox "X is a Big Number" Msgbox "X is a Big Number" Msgbox "X value is: "&X Msgbox "X value is: "&X Else

Else

Msgbox "GCR" Msgbox "GCR"

Msgbox "X is a Small Number" Msgbox "X is a Small Number" Msgbox "X value is: "&X

Msgbox "X value is: "&X End If 

End If 

8.1.4 Deciding Between Several Alternatives 8.1.4 Deciding Between Several Alternatives A variation on the

A variation on the If...Then...Else statement allows us to choose from severalIf...Then...Else statement allows us to choose from several alternatives. Adding ElseIf clauses expands the functionality of

alternatives. Adding ElseIf clauses expands the functionality of the If...Then...Elsethe If...Then...Else statement so we can control program flow

statement so we can control program flow based on different possibilities.based on different possibilities. Example:

Example: Dim x Dim x

x= Inputbox (" Enter a value") x= Inputbox (" Enter a value") If x>0 and x<=100 Then

If x>0 and x<=100 Then Msgbox "Hello Tester" Msgbox "Hello Tester"

Msgbox "X is a Small Number" Msgbox "X is a Small Number" Msgbox

Msgbox "X v"X value is alue is "&x"&x Else IF x>100 and x<=500 Then Else IF x>100 and x<=500 Then

Msgbox "Hello GCR" Msgbox "Hello GCR"

Msgbox "X is a Medium Number" Msgbox "X is a Medium Number" Else IF x>500 and x<=1000 Then

Else IF x>500 and x<=1000 Then Msgbox "Hello Tester" Msgbox "Hello Tester"

Msgbox "X is a Large Number" Msgbox "X is a Large Number" Else

Else

Msgbox "Hello Sir" Msgbox "Hello Sir"

Msgbox "X is a Grand Number" Msgbox "X is a Grand Number" End If  End If  End If  End If  End If  End If 

8.1.5 Executing a certain block of statements when two /

8.1.5 Executing a certain block of statements when two / more conditionsmore conditions are True (Nested If...)

are True (Nested If...) Example:

Example:

Dim State, Region Dim State, Region

State=Inputbox ("Enter a State") State=Inputbox ("Enter a State") Region=Inputbox ("Enter a Region") Region=Inputbox ("Enter a Region") If

If state= state= "AP" "AP" ThenThen

If Region= "Telangana" Then If Region= "Telangana" Then

(15)

msgbox "Hello Tester" msgbox "Hello Tester" msgbox "Dist count is 10" msgbox "Dist count is 10" Else if Region= "Rayalasema" Then Else if Region= "Rayalasema" Then msgbox "Hello GCR" msgbox "Hello GCR" msgbox "Dist count is 4" msgbox "Dist count is 4" Else If Region= "Costal" Then

Else If Region= "Costal" Then

msgbox "Hello Tester" msgbox "Hello Tester" msgbox "Dist count is 9" msgbox "Dist count is 9" End If  End If  End If  End If  End If  End If  End If  End If 

8.2 Making Decisions with Select Case

8.2 Making Decisions with Select Case

The Select Case structure provides an alternative to

The Select Case structure provides an alternative to If...Then...ElseIf for selectivelyIf...Then...ElseIf for selectively executing one block of statements from among

executing one block of statements from among multiple blocks of statements. Amultiple blocks of statements. A Select Case statement provides capability similar

Select Case statement provides capability similar to the If...Then...Else statement,to the If...Then...Else statement, but it makes code more efficient and readable.

but it makes code more efficient and readable. Example:

Example: Option explicit Option explicit

Dim x,y, Operation, Result Dim x,y, Operation, Result x= Inputbox (" Enter x value") x= Inputbox (" Enter x value") y= Inputbox ("Enter y value") y= Inputbox ("Enter y value")

Operation= Inputbox ("Enter an Operation") Operation= Inputbox ("Enter an Operation") Select Case Operation

Select Case Operation Case "add" Case "add"

Result= cdbl (x)+cdbl (y) Result= cdbl (x)+cdbl (y) Msgbox "Hello Tester" Msgbox "Hello Tester"

Msgbox "Addition of x,y values is

Msgbox "Addition of x,y values is "&Result"&Result Case "sub"

Case "sub"

Result= x-y Result= x-y

Msgbox "Hello Tester" Msgbox "Hello Tester"

Msgbox "Substraction of x,y values is "&Result Msgbox "Substraction of x,y values is "&Result Case "mul"

Case "mul"

Result= x*y Result= x*y

Msgbox "Hello Tester" Msgbox "Hello Tester"

Msgbox "Multiplication of x,y values is "&Result Msgbox "Multiplication of x,y values is "&Result Case "div"

Case "div"

Result= x/y Result= x/y

Msgbox "Hello Tester" Msgbox "Hello Tester"

Msgbox "Division of x,y values is

(16)

Case "mod" Case "mod"

Result= x mod y Result= x mod y Msgbox "Hello Tester" Msgbox "Hello Tester"

Msgbox "Mod of x,y values is "&Result Msgbox "Mod of x,y values is "&Result Case "expo"

Case "expo"

Result= x^y Result= x^y

Msgbox "Hello Tester" Msgbox "Hello Tester"

Msgbox"Exponentation of x,y values is "&Result Msgbox"Exponentation of x,y values is "&Result Case Else

Case Else

Msgbox "Hello Tester" Msgbox "Hello Tester" msgbox "Wrong Operation" msgbox "Wrong Operation" End Select

End Select

8.3 Other Examples

8.3 Other Examples

8.3.1 Write a program for finding out whether the given year is a leap year 8.3.1 Write a program for finding out whether the given year is a leap year or not?

or not? Dim xyear Dim xyear

xyear=inputbox ("Enter Year") xyear=inputbox ("Enter Year") If xyear mod 4=0 Then

If xyear mod 4=0 Then

msgbox "This is a Leap year" msgbox "This is a Leap year" Else

Else

msgbox "This is NOT" msgbox "This is NOT" End If 

End If 

8.3.2 Write a program for finding

8.3.2 Write a program for finding out whether the given number is, Evenout whether the given number is, Even number or Odd number?

number or Odd number? Dim num

Dim num

num=inputbox ("Enter a number") num=inputbox ("Enter a number") If num mod 2=0 Then

If num mod 2=0 Then

msgbox "This is a Even Number" msgbox "This is a Even Number" Else

Else

msgbox "This is a Odd Number" msgbox "This is a Odd Number" End If 

End If 

8.3.3 Read two numbers and display the sum? 8.3.3 Read two numbers and display the sum? Dim num1,num2, sum

Dim num1,num2, sum

num1=inputbox ("Enter num1") num1=inputbox ("Enter num1") num2=inputbox ("Enter num2") num2=inputbox ("Enter num2")

sum= Cdbl (num1) + Cdbl (num2) 'if we

sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversionwant add two strings conversion require

require

msgbox ("Sum is " &sum) msgbox ("Sum is " &sum)

(17)

8.3.4 Read

8.3.4 Read P,T,R P,T,R values and Cvalues and Calculate the Simpalculate the Simple Interest?le Interest? Dim p,t, r, si

Dim p,t, r, si

p=inputbox ("Enter Principle") p=inputbox ("Enter Principle") t=inputbox ("Enter Time") t=inputbox ("Enter Time")

r=inputbox ("Enter Rate of Interest") r=inputbox ("Enter Rate of Interest")

si= (p*t*r)/100 ' p= principle amount, t=time in

si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interestyears, r= rate of interest msgbox ("Simple Interest is " &si)

msgbox ("Simple Interest is " &si) 8.3.5 Read Fou

8.3.5 Read Four digit number, cr digit number, calculate & display alculate & display the sum of the the sum of the number ornumber or display Error message if the number is not a four digit number?

display Error message if the number is not a four digit number? Dim num, sum

Dim num, sum

num=inputbox ("Enter a Four digit number") num=inputbox ("Enter a Four digit number") If

If Len(num) Len(num) = = 4 Th4 Thenen sum=0

sum=0

sum=sum+nu

sum=sum+num mod m mod 1010

num=num/10 num=num/10

num= left (num, 3) num= left (num, 3) sum=sum+nu

sum=sum+num m mod mod 1010

num=num/10 num=num/10

num= left (num, 2) num= left (num, 2) sum=sum+n

sum=sum+num mod um mod 1010

num=num/10 num=num/10

num= left (num, 1) num= left (num, 1) sum=sum+nu

sum=sum+num mod m mod 1010 msgbox ("Sum is " &sum) msgbox ("Sum is " &sum) else

else

msgbox "Number, you entered is not a 4 digit number" msgbox "Number, you entered is not a 4 digit number" End If 

End If 

8.3.6 Read any Four-digit number and display

8.3.6 Read any Four-digit number and display the number in reverse order?the number in reverse order? Dim num,rev

Dim num,rev

num= inputbox("Enter a number") num= inputbox("Enter a number") If len(num)=4 Then

If len(num)=4 Then

rev=rev*10 + num mod 10 rev=rev*10 + num mod 10 num=num/10

num=num/10 num= left(num,3) num= left(num,3)

rev=rev*10 + num mod 10 rev=rev*10 + num mod 10 num=num/10

num=num/10 num= left(num,2) num= left(num,2)

rev=rev*10 + num mod 10 rev=rev*10 + num mod 10 num=num/10

num=num/10 num= left(num,1) num= left(num,1)

rev=rev*10 + num mod 10 rev=rev*10 + num mod 10

msgbox "Reverse Order of the number is "&rev msgbox "Reverse Order of the number is "&rev

(18)

Else Else

msgbox "Number, you entered is not a 4 digit number" msgbox "Number, you entered is not a 4 digit number" End If 

End If 

8.3.7 Read 4 subjects marks; calculate the

8.3.7 Read 4 subjects marks; calculate the Total marks and grade?Total marks and grade? (a) If average marks Greater than or equal to 75, grade is Distinction (a) If average marks Greater than or equal to 75, grade is Distinction b) If average marks Greater than or equal to 60 and less than 75

b) If average marks Greater than or equal to 60 and less than 75 , then grade is, then grade is First

First

c) If average marks Greater than or equal to 50 and less than 60 ,

c) If average marks Greater than or equal to 50 and less than 60 , then grade isthen grade is Second

Second

d) If average marks Greater than or equal to 40 and less than 50

d) If average marks Greater than or equal to 40 and less than 50 , then grade is, then grade is Third

Third

e) Minimum marks 35 for

e) Minimum marks 35 for any subject, otherwise 'no grade fail')any subject, otherwise 'no grade fail') Dim e,m,p,c, tot

Dim e,m,p,c, tot

e=inputbox ("Enter english Marks") e=inputbox ("Enter english Marks") m=inputbox ("Enter maths Marks") m=inputbox ("Enter maths Marks") p=inputbox ("Enter physics Marks") p=inputbox ("Enter physics Marks") c=inputbox ("Enter chemistry Marks") c=inputbox ("Enter chemistry Marks") tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c) tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c) msgbox tot

msgbox tot

If cdbl(e) >=35 and cdbl(m) >=35 and

If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and totcdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Then

>=300 Then

msgbox "Grade is Distinction" msgbox "Grade is Distinction" else If

else If cdbl(e) >=35 and cdbcdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=l(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot35 and cdbl(c) >=35 and tot >=240 and tot<300 Then

>=240 and tot<300 Then msgbox "Grade is First" msgbox "Grade is First" else If cdbl(e) >=35 and

else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tottot >=200 and tot<240 Then

>=200 and tot<240 Then

msgbox "Grade is Second" msgbox "Grade is Second" else If cdbl(e) >=35 and

else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tottot >=160 and tot<200 Then

>=160 and tot<200 Then

msgbox "Grade is Third" msgbox "Grade is Third" else

else

msgbox "No Grade, Fail" msgbox "No Grade, Fail" End If  End If  End If  End If  End If  End If  End If  End If 

8.3.8 Display Odd numbers up to 8.3.8 Display Odd numbers up to n?n? Dim num,n

Dim num,n

n=Inputbox ("Enter a Vaule") n=Inputbox ("Enter a Vaule") For num= 1 to n step 2

(19)

msgbox num msgbox num Next

Next

8.3.9 Display Even numbers up to 8.3.9 Display Even numbers up to n?n? Dim num,n

Dim num,n

n=Inputbox ("Enter a Vaule") n=Inputbox ("Enter a Vaule") For num= 2 to n step 2

For num= 2 to n step 2 msgbox num

msgbox num Next

Next

8.3.10 display natural numbers up to n and write in a text file? 8.3.10 display natural numbers up to n and write in a text file? Dim num, n, fso, myfile

Dim num, n, fso, myfile

n= inputbox ("Enter any Value") n= inputbox ("Enter any Value") num=1

num=1

For num= 1 to n step 1 For num= 1 to n step 1 Set fso=

Set fso= createobject ("scripting.filesystemobjectcreateobject ("scripting.filesystemobject")") set myfile=fso.opentextfile ("E:\gcr.txt", 8, true) set myfile=fso.opentextfile ("E:\gcr.txt", 8, true) myfile.writeline num myfile.writeline num myfile.close myfile.close Next Next

8.11 Display Natural numbers in

8.11 Display Natural numbers in reverse order up to n?reverse order up to n? Dim num,n

Dim num,n

n=Inputbox ("Enter a Vaule") n=Inputbox ("Enter a Vaule") For num=n to 1 step -1

For num=n to 1 step -1 msgbox num

msgbox num Next

Next

8.12 Display Natural n

8.12 Display Natural numbers sum up umbers sum up to n? to n? (Using For...Next (Using For...Next Loop)Loop) Dim num, n, sum

Dim num, n, sum

n= inputbox ("Enter a Value") n= inputbox ("Enter a Value") sum=0

sum=0

For num= 1 to n step 1 For num= 1 to n step 1 sum= sum+num sum= sum+num Next Next msgbox sum msgbox sum

8.13 Display Natural numbers sum up

8.13 Display Natural numbers sum up to n? (using While...Wend Loop)to n? (using While...Wend Loop) Dim num, n, sum

Dim num, n, sum

n= inputbox ("Enter a Value") n= inputbox ("Enter a Value") While num <=cdbl (n) While num <=cdbl (n) sum= sum+num sum= sum+num num=num+1 num=num+1 Wend Wend msgbox sum msgbox sum

(20)

8.14 Display Natural numbers sum up

8.14 Display Natural numbers sum up to n? (Using Do...Until...Loop)to n? (Using Do...Until...Loop) Dim num, n, sum

Dim num, n, sum

n= inputbox ("Enter a Value") n= inputbox ("Enter a Value") sum=0 sum=0 num=1 num=1 Do Do sum= sum+num sum= sum+num num=num+1 num=num+1

Loop Until num =cdbl (n+1) Loop Until num =cdbl (n+1)

msgbox sum msgbox sum

8.15 Write a Function for Natural

8.15 Write a Function for Natural Numbers sum up to n?Numbers sum up to n? Function NNumCou (n)

Function NNumCou (n) Dim num, sum

Dim num, sum sum=0

sum=0

For num= 1 to n step 1 For num= 1 to n step 1 sum= sum+num sum= sum+num Next Next msgbox sum msgbox sum End Function End Function

8.16 Verify weather the entered 10 digit value is a numeric value or not? 8.16 Verify weather the entered 10 digit value is a numeric value or not? Dim a,x,y,z,num

Dim a,x,y,z,num

num=Inputbox ("Enter a Phone Number") num=Inputbox ("Enter a Phone Number") d1= left (num,1)

d1= left (num,1) d10=Right (num,1) d10=Right (num,1)

d2=mid (num, 2, len (1)) d2=mid (num, 2, len (1)) d3=mid (num, 3, len (1)) d3=mid (num, 3, len (1)) d4=mid (num, 4, len (1)) d4=mid (num, 4, len (1)) d5=mid (num, 5, len (1)) d5=mid (num, 5, len (1)) d6=mid (num, 6, len (1)) d6=mid (num, 6, len (1)) d7=mid (num, 7, len (1)) d7=mid (num, 7, len (1)) d8=mid (num, 8, len (1)) d8=mid (num, 8, len (1)) d9=mid (num, 9, len (1)) d9=mid (num, 9, len (1))

If isnumeric (d1) = "Tr

If isnumeric (d1) = "True" and ue" and isnumeric (d2) = "Tisnumeric (d2) = "True" and isnumeric (d3) = rue" and isnumeric (d3) = "True""True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) =

and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) =

"True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isn

"True"and isnumeric (dumeric (d10) = 10) = "True" "True" ThenThen msgbox "It is a Numeric Value" msgbox "It is a Numeric Value" else

else

Msgbox "It is NOT Numeric" Msgbox "It is NOT Numeric" End If 

(21)

8.17 Verify weather the entered value is a 10 digit value or not and Numeric 8.17 Verify weather the entered value is a 10 digit value or not and Numeric value or not? (Using multiple if conditions)

value or not? (Using multiple if conditions) Dim a,x,y,z,num

Dim a,x,y,z,num

num=Inputbox ("Enter a Phone Number") num=Inputbox ("Enter a Phone Number") d1= left (num,1)

d1= left (num,1) d10=Right (num,1) d10=Right (num,1)

d2=mid (num, 2, len (1)) d2=mid (num, 2, len (1)) d3=mid (num, 3, len (1)) d3=mid (num, 3, len (1)) d4=mid (num, 4, len (1)) d4=mid (num, 4, len (1)) d5=mid (num, 5, len (1)) d5=mid (num, 5, len (1)) d6=mid (num, 6, len (1)) d6=mid (num, 6, len (1)) d7=mid (num, 7, len (1)) d7=mid (num, 7, len (1)) d8=mid (num, 8, len (1)) d8=mid (num, 8, len (1)) d9=mid (num, 9, len (1)) d9=mid (num, 9, len (1)) If len

If len (num) (num) =10 =10 ThenThen If isnumeric (d1) = "Tr

If isnumeric (d1) = "True" and ue" and isnumeric (d2) = "Tisnumeric (d2) = "True" and isnumeric (d3) = rue" and isnumeric (d3) = "True""True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) =

and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) =

"True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isn

"True"and isnumeric (dumeric (d10) = 10) = "True" "True" ThenThen msgbox "It is a Numeric Value" msgbox "It is a Numeric Value" End If 

End If  End If  End If  If

If len (len (num) <num) <> 10 > 10 ThenThen

Msgbox "It is NOT valid Number " Msgbox "It is NOT valid Number " End If 

(22)

Looping Through Code

Looping Through Code

o

o Looping allows us to run Looping allows us to run a group of statements repeatedly.a group of statements repeatedly. o

o Some loops repeat statements until a Some loops repeat statements until a condition is False;condition is False; o

o Others repeat statements until a Others repeat statements until a condition is True.condition is True. o

o There are also loops that There are also loops that repeat statements a specific number of repeat statements a specific number of times.times.

The following looping statements are available in VBScript: The following looping statements are available in VBScript:

o

o Do...Loop:Do...Loop: Loops while or until a condition is True.Loops while or until a condition is True. o

o While...Wend:While...Wend: Loops while a condition is Loops while a condition is True.True. o

o For...Next:For...Next: Uses a counter to run statements a Uses a counter to run statements a specified number of times.specified number of times. o

o For Each...Next:For Each...Next: Repeats a group of statements for each item in a collectionRepeats a group of statements for each item in a collection

or each element of an array. or each element of an array. 9.1 Using Do Loops

9.1 Using Do Loops

We can use Do...Loop statements to run a block of statements an indefinite number We can use Do...Loop statements to run a block of statements an indefinite number of times.

of times.

The statements are repeated either while a condition is True or until a condition The statements are repeated either while a condition is True or until a condition becomes True.

becomes True.

9.1.1 Repeating Statements While a Condition is True 9.1.1 Repeating Statements While a Condition is True

Repeats a block of statements while a condition is True or until a condition becomes Repeats a block of statements while a condition is True or until a condition becomes True True a) Do While condition a) Do While condition Statements Statements ---Loop Loop

Or, we can use this

Or, we can use this below syntax:below syntax: Example: Example: Dim x Dim x Do While x<5 x=x+1 Do While x<5 x=x+1

Msgbox "Hello Tester" Msgbox "Hello Tester" Msgbox "Hello QTP" Msgbox "Hello QTP" Loop Loop b) Do b) Do Statements Statements ---Loop

(23)

Example: Example: Dim x Dim x x=1 x=1 Do Do

Msgbox "Hello Tester" Msgbox "Hello Tester" Msgbox "Hello QTP" Msgbox "Hello QTP" x=x+1 x=x+1 Loop While x<5 Loop While x<5

9.1.2 Repeating a Statement Until a

9.1.2 Repeating a Statement Until a Condition Becomes TrueCondition Becomes True c)

c) Do Do Until Until conditioncondition Statements Statements ---Loop Loop

Or, we can use this

Or, we can use this below syntax:below syntax: Example: Example: Dim x Dim x Do Until x=5 x=x+1 Do Until x=5 x=x+1 Msgbox "Tester" Msgbox "Tester" Msgbox "Hello QTP" Msgbox "Hello QTP" Loop Loop

Or, we can use this

Or, we can use this below syntax:below syntax: d) Do d) Do Statements Statements

---Loop Until condition Loop Until condition Or, we can use this

Or, we can use this below syntax:below syntax: Example: Example: Dim x Dim x x=1 x=1 Do Do

Msgbox “Hello Tester”  Msgbox “Hello Tester”  Msgbox "Hello QTP" Msgbox "Hello QTP" x=x+1 x=x+1 Loop Until x=5 Loop Until x=5 9.2 While...Wend Statement 9.2 While...Wend Statement

Executes a series of statements as long as a given condition is True. Executes a series of statements as long as a given condition is True. Syntax: Syntax: While condition While condition Statements Statements

(24)

---Wend Wend Example: Example: Dim x Dim x x=0 x=0 While x<5 x=x+1 While x<5 x=x+1

msgbox "Hello Tester" msgbox "Hello Tester" msgbox "Hello QTP" msgbox "Hello QTP" Wend Wend 9.3 For...Next Statement 9.3 For...Next Statement

Repeats a group of statements a specified number of times. Repeats a group of statements a specified number of times. Syntax:

Syntax:

For counter = start to end

For counter = start to end [Step step][Step step] statements statements Next Next Example: Example: Dim x Dim x For x= 1 to 5 step 1 For x= 1 to 5 step 1 Msgbox "Hello Tester" Msgbox "Hello Tester" Next

Next

9.4 For Each...Next Statement 9.4 For Each...Next Statement

Repeats a group of statements for each element in an array or collection. Repeats a group of statements for each element in an array or collection. Syntax:

Syntax:

For Each item In array For Each item In array

Statements Statements Next Next Example: (1 Example: (1 Dim a,b,x (3) Dim a,b,x (3) a=20 a=20 b=30 b=30

x(0)= "Addition is "& a+b x(0)= "Addition is "& a+b x(1)="Substraction is " & a-b x(1)="Substraction is " & a-b x(2)=

x(2)= "Multiplication is "Multiplication is " & " & a*ba*b x(3)=

x(3)= "Division "Division is " is " & & a/ba/b For Each element In x For Each element In x msgbox element msgbox element Next Next Example: (2 Example: (2 MyArray =

MyArray = Array("one","twArray("one","two","three","four","five")o","three","four","five") For Each element In MyArray

(25)

msgbox element msgbox element Next

Next

Control Flow Examples

Control Flow Examples

(Using Conditional and Loop Statements)(Using Conditional and Loop Statements) 11.1 read a number and verify that number Range weather in between 1 to 11.1 read a number and verify that number Range weather in between 1 to 100 or 101 to 1000? 100 or 101 to 1000? Option explicit Option explicit Dim a,x Dim a,x

a=Inputbox ("Enter a Vaule") a=Inputbox ("Enter a Vaule") a=cdbl(a) a=cdbl(a) If a<= 100 Then If a<= 100 Then For x= 1 to 100 For x= 1 to 100 If a=x Then If a=x Then

msgbox "a is in between 1 to 100 range" msgbox "a is in between 1 to 100 range" End If  End If  Next Next else else For x= 101 to 1000 For x= 101 to 1000 If a=x Then If a=x Then

msgbox "a is in between 101 to 1000 range" msgbox "a is in between 101 to 1000 range" End If  End If  Next Next End If  End If 

11.1 read Data and find that data size, If

11.1 read Data and find that data size, If size <>4 then display invalid datasize <>4 then display invalid data message, if data size = 4

message, if data size = 4 then verify “a” is there or not in that data?then verify “a” is there or not in that data? Dim x

Dim x

x=Inputbox ("Enter 4 digit value") x=Inputbox ("Enter 4 digit value") x1=Right(x,1) x1=Right(x,1) x2=Left (x,1) x2=Left (x,1) x3=mid (x,2,Len(1)) x3=mid (x,2,Len(1)) x4=mid (x,3,Len(1)) x4=mid (x,3,Len(1)) y=len(x) y=len(x) If y=4 Then If y=4 Then If

If x1="a" or x1="a" or x2="a" or x2="a" or x3="a" or x3="a" or x4="a" Thenx4="a" Then msgbox "a is there"

msgbox "a is there" else

else

msgbox "a is Not there" msgbox "a is Not there" End If 

End If  else else

msgbox "Invalid Data" msgbox "Invalid Data" End If 

(26)

VB Script Procedures

VB Script Procedures

In VBScript, there are two kinds of

In VBScript, there are two kinds of procedures available; theprocedures available; the SubSub procedure and theprocedure and the Function

Function procedure.procedure. 11.1 Sub Procedures 11.1 Sub Procedures A Sub procedure is a

A Sub procedure is a series of VBScript statements (enclosed byseries of VBScript statements (enclosed by SubSub andand End SubEnd Sub statements) that perform actions but don't return a

statements) that perform actions but don't return a value.value. A Sub procedure can take arguments (constants, variables, or

A Sub procedure can take arguments (constants, variables, or expressions that areexpressions that are passed by a calling

passed by a calling procedure).procedure).

If a Sub procedure has no arguments, its Sub statement must include an empty set If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses ().

of parentheses (). Syntax:

Syntax:

Sub Procedure name () Sub Procedure name () Statements Statements ---End Sub End Sub Or Or

Sub Procedure name (argument1, argument2) Sub Procedure name (argument1, argument2) Statements Statements ---End Sub End Sub Example: 1 Example: 1 Sub ConvertTemp() Sub ConvertTemp()

temp = InputBox("Please enter the temperature in degrees F.", temp = InputBox("Please enter the temperature in degrees F.", 1)1) MsgBox "The temperature is " & Celsius(temp) & "

MsgBox "The temperature is " & Celsius(temp) & " degrees C."degrees C." End Sub End Sub Example: 2 Example: 2 11.2 Function Procedures 11.2 Function Procedures

A Function procedure is a series of

A Function procedure is a series of VBScript statements enclosed by theVBScript statements enclosed by the FunctionFunction andand End Function

End Function statements.statements.

A Function procedure is similar to a

A Function procedure is similar to a Sub procedure, but can also return a Sub procedure, but can also return a value.value. A Function procedure can take arguments (constants, variables, or expressions that A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure).

are passed to it by a calling procedure). If a Function procedure has no

If a Function procedure has no arguments, its Function statement must include anarguments, its Function statement must include an empty set of parentheses.

(27)

A Function returns a value by assigning a value to its name in one or more A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of

statements of the procedure. The return type of a Function is always a a Function is always a Variant.Variant. Syntax:

Syntax:

Function Procedure name () Function Procedure name () Statements Statements ---End Function End Function Or Or

Function Procedure name (argument1, argument2) Function Procedure name (argument1, argument2) Statements Statements ---End Function End Function Example: 1 Example: 1 Function Celsius(fDegrees) Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 Celsius = (fDegrees - 32) * 5 / 9 End Function End Function Example: 2 Example: 2 Function cal(a,b,c) Function cal(a,b,c) cal = (a+b+c) cal = (a+b+c) End Function End Function

11.3 Getting Data into and

11.3 Getting Data into and out of Proceduresout of Procedures

o

o Each piece of data Each piece of data is passed into our procedures using an is passed into our procedures using an argument.argument. o

o Arguments serve as placeholders for the data we Arguments serve as placeholders for the data we want to pass into ourwant to pass into our

procedure. We can name our arguments any valid variable name. procedure. We can name our arguments any valid variable name.

o

o When we create a procedure using either When we create a procedure using either the Sub statement or the Functionthe Sub statement or the Function

statement, parentheses must be included after the

statement, parentheses must be included after the name of the procedure.name of the procedure.

o

o Any arguments are placed inside these parentheses, separated Any arguments are placed inside these parentheses, separated by commas.by commas.

11.4 Using Sub and Function Procedures in Code 11.4 Using Sub and Function Procedures in Code

A Function in our code must always be used on the right side of a variable A Function in our code must always be used on the right side of a variable assignment or in an expression. assignment or in an expression. For example: For example: Temp = Celsius(fDegrees) Temp = Celsius(fDegrees)

-Or-MsgBox "The Celsius temperature is " &

MsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."Celsius(fDegrees) & " degrees." To call a

To call a Sub procedure from another procedure, type the name of Sub procedure from another procedure, type the name of the procedurethe procedure along with values for any required arguments, each separated by a comma. along with values for any required arguments, each separated by a comma.

(28)

The Call statement is not required, but if you do use it, you must enclose any The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses.

arguments in parentheses.

The following example shows two calls to

The following example shows two calls to the MyProc procedure. One uses the Callthe MyProc procedure. One uses the Call statement in the code; the

statement in the code; the other doesn't. Both do exactly the other doesn't. Both do exactly the same thing.same thing. Call MyProc(firstarg, secondarg)

Call MyProc(firstarg, secondarg) MyProc firstarg, secondarg

MyProc firstarg, secondarg

Notice that the parentheses are omitted in the call when the Call statement isn't Notice that the parentheses are omitted in the call when the Call statement isn't used.

(29)

VB Script Built in Functions

VB Script Built in Functions

Types of Functions Types of Functions o o Conversions (25)Conversions (25) o o Dates/Times (19)Dates/Times (19) o

o Formatting Strings (4)Formatting Strings (4) o o Input/Output (3)Input/Output (3) o o Math (9)Math (9) o o Miscellaneous (3)Miscellaneous (3) o o Rounding (5)Rounding (5) o o Strings (30)Strings (30) o o Variants (8)Variants (8) Important Functions Important Functions 1) Abs Function 1) Abs Function

Returns the absolute value of a number. Returns the absolute value of a number. Dim num Dim num num=abs(-50.33) num=abs(-50.33) msgbox num msgbox num 2) Array Function 2) Array Function

Returns a variant containing an Array Returns a variant containing an Array Dim A Dim A A=Array("hyderabad","chennai","mumbai") A=Array("hyderabad","chennai","mumbai") msgbox A(0) msgbox A(0) ReDim A(5) ReDim A(5) A(4)="nellore" A(4)="nellore" msgbox A(4) msgbox A(4) 3) Asc Function 3) Asc Function

Returns the ANSI character code corresponding to the first

Returns the ANSI character code corresponding to the first letter in a string.letter in a string. Dim num Dim num num=Asc("A") num=Asc("A") msgbox num msgbox num

* It returns the value 65 * * It returns the value 65 * 4) Chr Function

4) Chr Function

Returns the character associated with the specified ANSI

Returns the character associated with the specified ANSI character code.character code. Dim char Dim char Char=Chr(65) Char=Chr(65) msgbox char msgbox char

(30)

* It returns A * * It returns A * 5) CInt Function 5) CInt Function

Returns an expression that has been

Returns an expression that has been converted to aconverted to a VariantVariant of subtypeof subtype IntegerInteger.. Dim num Dim num num=123.45 num=123.45 myInt=CInt(num) myInt=CInt(num) msgbox MyInt msgbox MyInt 6) Date Function 6) Date Function

Returns the Current System Date. Returns the Current System Date. Dim mydate Dim mydate mydate=Date mydate=Date msgbox mydate msgbox mydate 7) Day Function 7) Day Function Ex1)

Ex1) Dim Dim mydaymyday

myday=Day("17,December,2009") myday=Day("17,December,2009") msgbox myday msgbox myday E Exx22)) DDiim m mmyyddaayy mydate=date mydate=date myday=Day(Mydate) myday=Day(Mydate) msgbox myday msgbox myday 8) DateDiff Function 8) DateDiff Function

Returns the number of intervals between two

Returns the number of intervals between two dates.dates. Dim myday Dim myday mydate=#02-17-2009# mydate=#02-17-2009# x=Datediff("d",mydate,Now) x=Datediff("d",mydate,Now) msgbox x msgbox x 9) Hour Function 9) Hour Function

Returns a whole number between 0

Returns a whole number between 0 and 23, inclusive, representing the hour of and 23, inclusive, representing the hour of thethe day.

day.

Dim mytime, Myhour Dim mytime, Myhour mytime=Now mytime=Now myhour=hour (mytime) myhour=hour (mytime) msgbox myhour msgbox myhour 10) Join Function 10) Join Function

Returns a string created by

Returns a string created by joining a number of substrings contained in an joining a number of substrings contained in an array.array. Dim mystring, myarray(3)

Dim mystring, myarray(3) myarray(0)="Chandra " myarray(0)="Chandra " myarray(1)="Mohan " myarray(1)="Mohan " myarray(2)="Tester" myarray(2)="Tester" mystring=Join(MyArray) mystring=Join(MyArray) msgbox mystring msgbox mystring

References

Related documents

Example in macro variables in second one or statement during that are at run multiple values in method calls another object variable cannot be allocated by using. You want want

In the glory we declare your hearts were sufficiently declaring the humanists of your glory of a humble you most high school, with an everlasting king this aspect of hebrew

In java date conversion characters called dictionaries or constant in the constants, dates are declared outside of an object to.. If the constants in

Returns an expression instead of the regular expression in javascript multiple lines is not declared in the string nor your open files to a function with.. The characters as

declarations declare a declaration to better code like other declared explicitly declare constants have a static modifier to declare, declaring an implicitly converted from

Represent a change to declare constant integer vba constants and whatnot in a constant declared with dim statement and final part is what is another example.. Me with a as integer

Java application data sources csv, hour for constructing the java and time is necessary to do i know about assignment to a date object source objects have any metadata declared..

What groovy in a list using it is declared with quite neat, null from groovy fits in the declaration, allowing standalone literals and declare array.. Create a parameter to a