Anda di halaman 1dari 154

For more QTP Realtime Sripts, visit

www.ramupalanki.com
VB Script For QTP 1

Script
For
QTP
VB Script For QTP 2

VB Script Comments

Comments

The comment argument is the text of any comment we want to include.

Purpose of comments:

o We can use comments for making the script understandable.

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


from execution.

Syntax

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

Or

Apostrophe (') symbol before the comment

Comment/Uncomment a block of statements

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

o Select comment block and use short cut key Ctrl + Shift + M (for uncomment)
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 3

VB Script Variables

Definition 1):

Variable is a named memory location for storing program information


Definition 2):
A variable is a convenient placeholder that refers to a computer memory location
where we can store program information that may change during the time our
script is running.

Purpose of Variable:

a) Comparing values

Example:

Dim x,y,a
x=100
y=100
a=x=y

Msgbox a 'It returns True

b) Holding Program Result

Example:

Cost=Tickets*Price

c) Passing parameters
d) To store data that returned by
functions Example:

myDate=Now ‘ It returns current data & time

e) To hold data

Example:

myName=”gcreddy”

Declaring Variables

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

For example:

Dim city

Dim x

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


For
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 4

Example:

Dim x, y, city, gcreddy

We can also declare a variable implicitly by simply using its name in our script.
That 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 run.
For that reason, the Option Explicit statement is available to require explicit
declaration of all variables.

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

Option Explicit Statement

Forces explicit declaration of all variables in a script.

Option Explicit ' Force explicit variable declaration.

Dim MyVar ' Declare variable.

MyInt = 10 ' Undeclared variable generates error.

MyVar = 10 ' Declared variable does not generate error.


Naming Restrictions for Variables

Variable names follow the standard rules for naming anything in VBScript. A
variable name:
a) Must begin with an alphabetic character.

Dim abc 'Right

Dim 9ab 'Wrong

Dim ab9 'Right

b) Cannot contain an embedded period.

Dim abc 'Right

Dim ab.c 'worng

Dim ab-c 'wrong

Dim ab c 'wrong

Dim ab_c 'Right

c) Must not exceed 255 characters.

d) Must be unique in the scope in which it is declared.

Scope of Variables

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

When we declare a variable within a procedure, only code within that procedure
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 5

can access or change the value of that variable.

If we declare a variable outside a procedure, we make it recognizable to all the


procedures in our script. This is a script-level variable, and it has script-level
scope.

Example:
Dim x,y,z

x=10
y=20

z=x+y
msgbox z 'Returns 30

Function res
Dim
a,b,c

a=30
b=40

c=a+b+y
msgbox
c ' Returns 90

End Function
Call res

Life Time of Variables

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 time the script is finished running.
At procedure level, a variable exists only as long as you are in the procedure.

Assigning Values to Variables

Values are assigned to variables creating an expression as follows:

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

For example:

A = 200

City = “Hyderabad”

X=100: Y=200

Scalar Variables and Array Variables

A variable containing a single value is a scalar variable.

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


For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 6

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.

Example:

Dim A(3)

Although the number shown in the parentheses is 3, all arrays in VBScript


are zero-based, so this array actually contains 4 elements.

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

Beginning at zero and ending at 4, data can be assigned to the elements of an


array as follows:

A(0) = 256

A(1) = 324

A(2) = 100

A(3) = 55

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

For example:
SomeVariable = A(4)

Arrays aren't limited to a single dimension. We can have as many as 60


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

In the following example, the MyTable variable is a two-dimensional array


consisting of 6 rows and 11 columns:

Dim MyTable(5, 10)

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


the second number is the number of columns.

Dynamic Arrays

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

The array is initially declared within a procedure using either the Dim
statement or using the ReDim statement.
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 7

However, for a dynamic array, no size or number of dimensions is placed


inside the parentheses.

For example:

Dim MyArray()

ReDim AnotherArray()

To use a dynamic array, you must subsequently use ReDim to determine


the number of dimensions and the size of each dimension.

In the following example, ReDim sets the initial size of the dynamic array to 25. A
subsequent ReDim statement resizes the array to 30, but uses the Preserve
keyword to preserve the contents of the array as the resizing takes place.

ReDim MyArray(25)

ReDim Preserve MyArray(30)

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 elimina
VB Script For QTP 8

VB Script Data Types

VBScript has only one data type called a Variant. A Variant is a special kind of
data type that can contain different kinds of information, depending on how it is
used. Because Variant is the only data type in VBScript, it is also the data type
returned by all functions in VBScript.

Variant Subtypes

Beyond the simple numeric or string classifications, a Variant can make further
distinctions about the specific nature of numeric information. For example, we
can 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 have a rich variety of numeric information ranging in size from Boolean
values to huge floating-point numbers. These different categories of information
that can be 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 Variant behaves in a way
that is most appropriate for the data it contains.

The following table shows subtypes of data that a Variant can contain.
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 9

VB Script Operators

Operators are used for performing mathematical, comparison and


logical operations.

VB Script has a full range of operators, including arithmetic operators,


comparison operators, concatenation operators, and logical operators.

Operator Precedence

When several operations occur in an expression, each part is evaluated and


resolved in a predetermined order called operator precedence.

We can use parentheses to override the order of precedence and force


some parts of an expression to be evaluated before others.

Operations within parentheses are always performed before those outside.


Within parentheses, however, standard operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic
operators are evaluated first, comparison operators are evaluated next, and
logical operators are evaluated last.

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

Arithmetic and logical operators are evaluated in the following order of


precedence.
1) Arithmetic Operators:

Operator Description

1) Exponentiation Operator (^) Raises a number to the power of an exponent

2) Multiplication Operator (*) Multiplies two numbers.

3) Division Operator (/) Divides two numbers and returns a floating-


point result.

4) Integer Division Operator (\) Divides two numbers and returns an


integer result.

5) Mod Operator Divides two numbers and returns only the remainder.

6) Addition Operator (+) Sums two numbers.


For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 10

7) Subtraction Operator (-) Finds the difference between two


numbers or indicates the negative value of a numeric expression.

8) Concatenation Operator (&) Forces string concatenation of two


expressions.

Example:

Dim a,b,c
a=10 b=3
c=a^b

msgbox c '1000

c=a*b
msgbox c '30

c=a/b

msgbox c '3.33333333

c=a\b
msgbox c '3

c=a mod b
msgbox c '1
c=a-b
msgbox c '7

Dim a,b,c
a=10 b=2

c=3
d=c*a^b
'c=a+b

msgbox d '1000

Addition (+) operator

Dim a,b,c
a=10 b=2
c=a+b

msgbox c '12 (if both are numeric, then it adds)

a="10"
b=2
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 11

c=a+b
msgbox c '12 (one is string another numeric, then it adds)

a="10"
b="2"
c=a+b

msgbox c '102 (if both are strings, then it concatenates)

a="hydera"
b="bad"
c=a+b

msgbox c 'hyderabad

a="gagan"
b=2
c=a+b

msgbox c 'error

Concatenation Operator

Dim a,b,c
a=10 b=2
c=a&b

msgbox c '102

a="10"
b=2
c=a&b
msgbox c '102

a="10"
b="2"
c=a&b

msgbox c '102

a="hydera"
b="bad" c=a&b
msgbox c '102

2) Comparison Operators

Used to compare expressions.

Operator Description
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 12

1) = (Equal to) Used to compare expressions.

2) <> (Not equal to) Used to compare expressions.

3) < Less than 4) > Grater than


5) <= Less than or equal to 6) >= Greater than or equal to

7) Is Object equivalence

3) Concatenation Operators

Operator Description

1) Addition Operator (+)

Sums two numbers

If Then

1) Both expressions are numeric Add.

2) Both expressions are strings Concatenate.

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

2) Concatenation Operator (&) Forces string concatenation of two expressions.


4) Logical Operators

Operator Description Syntax

1) Not Performs logical negation on an expression result= Not expression

2) And Performs a logical conjunction on two expressions. result=


expression1 And expression2

3) Or Performs a logical disjunction on two expressions. result=


expression1 Or expression2

4) Xor Performs a logical exclusion on two expressions. result=


expression1 Xor expression2

5) Eqv Performs a logical equivalence on two expressions. result=


expression1 Eqv expression2

6) Imp Performs a logical implication on two expressions. result=


expression1

Imp expression2
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 13

Input and Out Put Operations

InputBox Function

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.

Example:

Dim Input

Input = InputBox("Enter your name")

MsgBox ("You entered: " & Input)

MsgBox Function

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

Example:

Dim MyVar

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

MyVar contains either 1 or 2, depending on which button is clicked.


VB Script For QTP 14

VB Script Constants

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

Creating Constants

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


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

Const statement

Declares constants for use in place of literal values.

Example:

Const MyString = "This is my string."

Const MyAge = 49

Const CutoffDate = #6-1-97#

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


For more QTP Realtime Sripts, visit
www.ramupalanki.com
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 comma. For example:

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


VB Script For QTP 15

Conditional Statements

Flow Control (Conditional Statements)

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

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

VBScript:

1) If…Then…Else Statement

2) Select Case Statement

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

The If...Then...Else statement is used to evaluate whether a condition is True or

False and, depending on the result, to specify one or more statements to run.

Usually the condition is an expression that uses a comparison operator


to compare one value or variable with another.

If...Then...Else statements can be nested to as many levels as you need.


For more QTP Realtime Sripts, visit
www.ramupalanki.com
1) Running a Statement if a Condition is True (single statement)

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

Dim myDate
myDate = #2/13/98#

If myDate < Now Then myDate = Now

2) Running Statements if a Condition is True (multiple statements)

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

Dim x

x= 20

If x>10 Then

msgbox "x value is: "&x


msgbox "Bye Bye" End
If
VB Script For QTP 16

3) Running Certain Statements if a Condition is True and Running Others


if a Condition is False

We can use an If...Then...Else statement to define two blocks of executable


statements: one block to run if the condition is True, the other block to run if
the condition is False.

Example:

Dim x

x= Inputbox (" Enter a


value") If x>100 Then

Msgbox "Hello G.C.Reddy"


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

Else

Msgbox "GCR"

Msgbox "X is a Small Number"

Msgbox "X value is: "&X


End If

4) Deciding Between Several Alternatives

A variation on the Then.. Else statement allows us to choose from


If... . several
alternatives. Adding ElseIf clauses expands the functionality of the
If.. Then.. Else statement so we can control program flow based on different
For more QTP Realtime Sripts, visit
www.ramupalanki.com
. .

possibilities.

Example:

Dim x

x= Inputbox (" Enter a value")

If x>0 and x<=100 Then

Msgbox "Hello G.C.Reddy"

Msgbox "X is a Small Number"

Msgbox "X value is "&x

Else IF x>100 and x<=500 Then

Msgbox "Hello GCR"

Msgbox "X is a Medium Number"

Else IF x>500 and x<=1000 Then

Msgbox "Hello Chandra Mohan Reddy"

Msgbox "X is a Large Number"

Else
VB Script For QTP 17

Msgbox "Hello Sir"

Msgbox "X is a Grand Number"

End If

End If
End If

5) Executing a certain block of statements when two / more conditions are


True (Nested If...)

Example:

Dim State, Region

State=Inputbox ("Enter a State")

Region=Inputbox ("Enter a Region")

If state= "AP" Then

If Region= "Telangana" Then


msgbox "Hello G.C.Reddy"
msgbox "Dist count is 10"

Else if Region= "Rayalasema"


Then msgbox "Hello GCR"

msgbox "Dist count is 4"

Else If Region= "Costal" Then


For more QTP Realtime Sripts, visit
www.ramupalanki.com
msgbox "Hello Chandra mohan Reddy"
msgbox "Dist count is 9"

End If

End If

End If
End If

Making Decisions with Select Case

The Select Case structure provides an alternative to If...Then...ElseIf for


selectively executing one block of statements from among multiple blocks of
statements. A Select Case statement provides capability similar to the
If...Then...Else statement, but it makes code more efficient and readable.

Example:

Option explicit

Dim x,y, Operation, Result


x= Inputbox (" Enter x value")
y= Inputbox ("Enter y value")

Operation= Inputbox ("Enter an Operation")


VB Script For QTP 18

Select Case Operation

Case "add"

Result= cdbl (x)+cdbl (y)

Msgbox "Hello G.C.Reddy"

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

Case "sub"

Result= x-y

Msgbox "Hello G.C.Reddy"

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

Case "mul"

Result= x*y

Msgbox "Hello G.C.Reddy"

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

Case "div"

Result= x/y

Msgbox "Hello G.C.Reddy"


Msgbox "Division of x,y values is "&Result
For more QTP Realtime Sripts, visit
www.ramupalanki.com

Case "mod"

Result= x mod y

Msgbox "Hello G.C.Reddy"

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

Case "expo"

Result= x^y

Msgbox "Hello G.C.Reddy"


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

Case Else

Msgbox "Hello G.C.Reddy"

msgbox "Wrong Operation"

End Select
VB Script For QTP 19

VB Script Constants

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

Creating Constants

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


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

Const statement

Declares constants for use in place of literal values.

Example:

Const MyString = "This is my string."

Const MyAge = 49

Const CutoffDate = #6-1-97#

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


For more QTP Realtime Sripts, visit
www.ramupalanki.com
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 comma. For example:

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


VB Script For QTP 20

Conditional Statements

Flow Control (Conditional Statements)

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

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

VBScript:

1) If…Then…Else Statement

2) Select Case Statement

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

The If...Then...Else statement is used to evaluate whether a condition is True or

False and, depending on the result, to specify one or more statements to run.

Usually the condition is an expression that uses a comparison operator


to compare one value or variable with another.

If...Then...Else statements can be nested to as many levels as you need.


For more QTP Realtime Sripts, visit
www.ramupalanki.com
1) Running a Statement if a Condition is True (single statement)

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

Dim myDate
myDate = #2/13/98#

If myDate < Now Then myDate = Now

2) Running Statements if a Condition is True (multiple statements)

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

Dim x

x= 20

If x>10 Then

msgbox "x value is: "&x


msgbox "Bye Bye" End
If
VB Script For QTP 21

3) Running Certain Statements if a Condition is True and Running Others


if a Condition is False

We can use an If...Then...Else statement to define two blocks of executable


statements: one block to run if the condition is True, the other block to run if
the condition is False.

Example:

Dim x

x= Inputbox (" Enter a


value") If x>100 Then

Msgbox "Hello G.C.Reddy"


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

Else

Msgbox "GCR"

Msgbox "X is a Small Number"

Msgbox "X value is: "&X


End If

4) Deciding Between Several Alternatives

A variation on the Then.. Else statement allows us to choose from


If... . several
alternatives. Adding ElseIf clauses expands the functionality of the
If.. Then.. Else statement so we can control program flow based on different
For more QTP Realtime Sripts, visit
www.ramupalanki.com
. .

possibilities.

Example:

Dim x

x= Inputbox (" Enter a value")

If x>0 and x<=100 Then

Msgbox "Hello G.C.Reddy"

Msgbox "X is a Small Number"

Msgbox "X value is "&x

Else IF x>100 and x<=500 Then

Msgbox "Hello GCR"

Msgbox "X is a Medium Number"

Else IF x>500 and x<=1000 Then

Msgbox "Hello Chandra Mohan Reddy"

Msgbox "X is a Large Number"

Else
VB Script For QTP 22

Msgbox "Hello Sir"

Msgbox "X is a Grand Number"

End If

End If
End If

5) Executing a certain block of statements when two / more conditions are


True (Nested If...)

Example:

Dim State, Region

State=Inputbox ("Enter a State")

Region=Inputbox ("Enter a Region")

If state= "AP" Then

If Region= "Telangana" Then


msgbox "Hello G.C.Reddy"
msgbox "Dist count is 10"

Else if Region= "Rayalasema"


Then msgbox "Hello GCR"

msgbox "Dist count is 4"

Else If Region= "Costal" Then


For more QTP Realtime Sripts, visit
www.ramupalanki.com
msgbox "Hello Chandra mohan Reddy"
msgbox "Dist count is 9"

End If

End If

End If
End If

Making Decisions with Select Case

The Select Case structure provides an alternative to If...Then...ElseIf for


selectively executing one block of statements from among multiple blocks of
statements. A Select Case statement provides capability similar to the
If...Then...Else statement, but it makes code more efficient and readable.

Example:

Option explicit

Dim x,y, Operation, Result


x= Inputbox (" Enter x value")
y= Inputbox ("Enter y value")

Operation= Inputbox ("Enter an Operation")


VB Script For QTP 23

Select Case Operation

Case "add"

Result= cdbl (x)+cdbl (y)

Msgbox "Hello G.C.Reddy"

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

Case "sub"

Result= x-y

Msgbox "Hello G.C.Reddy"

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

Case "mul"

Result= x*y

Msgbox "Hello G.C.Reddy"

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

Case "div"

Result= x/y

Msgbox "Hello G.C.Reddy"


Msgbox "Division of x,y values is "&Result
For more QTP Realtime Sripts, visit
www.ramupalanki.com

Case "mod"

Result= x mod y

Msgbox "Hello G.C.Reddy"

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

Case "expo"

Result= x^y

Msgbox "Hello G.C.Reddy"


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

Case Else

Msgbox "Hello G.C.Reddy"

msgbox "Wrong Operation"

End Select
VB Script For QTP 24

Looping Through Code

Flow Control (Loop Statements)

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


o Some loops repeat statements until a condition is False;

o Others repeat statements until a condition is True.

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


times. The following looping statements are available in VBScript:

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


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

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

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


each element of an array.

1) Using Do Loops

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


indefinite number of times.

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


condition becomes True.

a) Repeating Statements While a Condition is True


For more QTP Realtime Sripts, visit
www.ramupalanki.com
Repeats a block of statements while a condition is True or until a
condition becomes True

i) Do While condition
Statements

-----------

-----------

Loop

Or, we can use this below syntax:

Example:

Dim x

Do While x<5 x=x+1

Msgbox "Hello G.C.Reddy"

Msgbox "Hello QTP"

Loop

ii) Do

Statements

-----------
VB Script For QTP 25

-----------

Loop While condition

Example:

Dim x
x=1

Do

Msgbox "Hello G.C.Reddy"


Msgbox "Hello QTP"
x=x+1

Loop While x<5

b) Repeating a Statement Until a Condition Becomes True

iii) Do Until condition


Statements

-----------

-----------

Loop
Or, we can use this below
syntax: Example:

Dim x
For more QTP Realtime Sripts, visit
www.ramupalanki.com
Do Until x=5 x=x+1

Msgbox "G.C.Reddy"

Msgbox "Hello QTP"

Loop

Or, we can use this below syntax:

iv) Do
Statements

-----------

-----------

Loop Until condition

Or, we can use this below syntax:

Example:

Dim x

x=1

Do

Msgbox “Hello G.C.Reddy”

Msgbox "Hello QTP"


VB Script For QTP 26

x=x+1

Loop Until x=5

2 While...Wend Statement

Executes a series of statements as long as a given condition is True.

Syntax:

While condition

Statements

-----------

-----------

Wend

Example:

Dim x
x=0

While x<5 x=x+1

msgbox "Hello G.C.Reddy"


msgbox "Hello QTP" Wend
For more QTP Realtime Sripts, visit
www.ramupalanki.com
3) For...Next Statement

Repeats a group of statements a specified number of times.

Syntax:

For counter = start to end [Step step]


statements
Next

Example:

Dim x

For x= 1 to 5 step 1

Msgbox "Hello G.C.Reddy"

Next

4) For Each...Next Statement

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

Syntax:

For Each item In array

Statements

Next
VB Script For QTP 27

Example: (1

Dim a,b,x (3)


a=20

b=30

x(0)= "Addition is "& a+b


x(1)="Substraction is " & a-b
x(2)= "Multiplication is " & a*b
x(3)= "Division is " & a/b

For Each element In


x msgbox element

Next

Example: (2

MyArray = Array("one","two","three","four","five")

For Each element In


MyArray msgbox element

Next
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 28

VB Script Procedures

User Defined Functions

In VBScript, there are two kinds of procedures available; the Sub procedure
and the Function procedure.

1) Sub Procedures

A Sub procedure is a series of VBScript statements (enclosed by Sub and End


Sub statements) that perform actions but don't return a value.

A Sub procedure can take arguments (constants, variables, or expressions


that are passed by a calling procedure).

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

Syntax:

Sub Procedure name ()

Statements

-----------

-----------
End
Sub Or
Sub Procedure name (argument1,
argument2) Statements

-----------

-----------

End Sub

Example: 1

Sub ConvertTemp()

temp = InputBox("Please enter the temperature in degrees F.", 1)

MsgBox "The temperature is " & Celsius(temp) & " degrees


C." End Sub

Example: 2

2) Function Procedures

A Function procedure is a series of VBScript statements enclosed by the


Function and End Function statements.
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 29

A Function procedure is similar to a Sub procedure, but can also return a value.

A Function procedure can take arguments (constants, variables, or expressions


that are passed to it by a calling procedure).

If a Function procedure has no arguments, its Function statement must include


an empty set of parentheses.

A Function returns a value by assigning a value to its name in one or more


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

Function Procedure name ()


Statements

-----------
-----------

End Function
Or
Function Procedure name (argument1, argument2)

Statements

-----------
-----------

End Function

Example: 1
Function Celsius(fDegrees)

Celsius = (fDegrees - 32) * 5 / 9

End Function

Example: 2

Function cal(a,b,c)
cal = (a+b+c)

End Function

3) Getting Data into and out of Procedures

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


o Arguments serve as placeholders for the data we want to pass into our
procedure. We can name our arguments any valid variable name.

o When we create a procedure using either the Sub statement or the Function
statement, parentheses must be included after the name of the procedure.
o Any arguments are placed inside these parentheses, separated by commas.

4) Using Sub and Function Procedures in Code


For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 30

A Function in our code must always be used on the right side of a variable
assignment or in an expression.

For example:

Temp = Celsius(fDegrees)
-Or-

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

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

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

The following example shows two calls to the MyProc procedure. One uses the

Call statement in the code; the other doesn't. Both do exactly the same thing.

Call MyProc(firstarg, secondarg)

MyProc firstarg, secondarg

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

(here, I used Flight Reservation Application for creating Functions, why because, It
is the default application for QTP, anybody can practice easily...G C Reddy)

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

' Login Operation

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

Function Login(Agent,Pwd)

SystemUtil.Run "C:\Program Files\HP\QuickTest

Professional\samples\flight\app\flight4a.exe"

Dialog("Login").Activate

Dialog("Login").WinEdit("Agent Name:").Set Agent

Dialog("Login").WinEdit("Password:").Set Pwd
Dialog("Login").WinButton("OK").Click

If Window("Flight Reservation").Exist(10) Then

Login="Login Operation Sucessful"

'Msgbox
Login else

Login="Login Operation Unsucessful"

Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 31

Dialog("Login").WinButton("Cancel").Click

'Msgbox Login

End If

End Function

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

' Closing Application

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

Function Close_App()

if Window("Flight Reservation").Exist(3) Then

Window("Flight Reservation").Close

End If

End Function

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

' Open Order


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

Function Open_Order(ord)
ordnum=0

On Error Resume Next


Window("Flight Reservation").Activate
Window("Flight Reservation").WinButton("Button").Click

Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order


No.").Set "ON"

Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set ord

Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click


ordnum=Window("Flight Reservation").WinEdit("Order No:").GetROProperty
("text")

ordnum=cdbl (ordnum)
If ord=ordnum Then
Open_Order= "Order Number "&ordnum&" Opened Sucuessfully"
'Msgbox Open_Order

else

Open_Order= "Order Number "&ordnum&" Not Opened/ Not Available"


Window("Flight Reservation").Dialog("Open Order").Dialog("Flight

Reservations").WinButton("OK").Click

Window("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click

'Msgbox Open_Order
End If
End Function

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

' Update Order

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

Function Update_Order(Tickets)

Window("Flight Reservation").Activate
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 32

Window("Flight Reservation").WinEdit("Tickets:").Set Tickets


Window("Flight Reservation").WinButton("Update
Order").Click wait(10)

update=Window("Flight Reservation").ActiveX("Threed Panel

Control").GetROProperty ("text")
If update="Update Done..." Then

Update_Order= "Order Updated


Sucussfully" 'Msgbox Update_Order
Else

Window("Flight Reservation").Dialog("Flight
Reservations").WinButton("OK").Click
Update_Order= "Order Not Updated"

'Msgbox Update_Order
End If
End Function

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

' Function to send a mail

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

Function SendMail(SendTo, Subject, Body, Attachment)


Set otl=CreateObject("Outlook.Application")

Set m=otl.CreateItem(0)
m.to=SendTo
m.Subject=Subject
m.Body=Body
If (Attachment <> "") Then
Mail.Attachments.Add(Attachment)

End If
m.Send
otl.Quit

Set m = Nothing
Set otl = Nothing
End Function

Call SendMail("gcreddy@gcreddy.com","hi","This is test mail for testing","")


For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 33

VB Script Errors

Generally Errors in VB Script are 2 Types

1) VB Script Run-time Errors

VB Script 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

48 Error in loading DLL

5020 Expected ')' in regular expression

5019 Expected ']' in regular expression


432 File name or class name not found during Automation operation
92 For loop not initialized
5008 Illegal assignment

51 Internal error

505 Invalid or unqualified reference

481 Invalid picture

5 Invalid procedure call or argument

5021 Invalid range in character set

94 Invalid use of Null

448Named argument not found

447Object doesn't support current locale setting

445Object doesn't support this action

438Object doesn't support this property or method

451Object not a collection

504Object not safe for creating

503Object not safe for initializing

502Object not safe for scripting

424Object required

91 Object variable not set

7 Out of Memory

28 Out of stack space


For more QTP Realtime Sripts, visit
www.ramupalanki.com
14 Out of string space

6 Overflow
VB Script For QTP 34

35 Sub or function not defined

9 Subscript out of range

5017 Syntax error in regular expression

462 The remote server machine does not exist or is unavailable


10 This array is fixed or temporarily locked

13 Type mismatch

5018 Unexpected quantifier

500 Variable is undefined


458 Variable uses an Automation type not supported in VBScript
450 Wrong number of arguments or invalid property assignment

2) 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:

1052 Cannot have multiple default property/method in a Class

1044 Cannot use parentheses when calling a Sub

1053 Class initialize or terminate do not have arguments


For more QTP Realtime Sripts, visit
www.ramupalanki.com
1058 'Default' specification can only be on Property Get

1057 'Default' specification must also specify 'Public'

1005 Expected '('

1006 Expected ')'

1011 Expected '='

1021 Expected 'Case'

1047 Expected 'Class'


1025 Expected end of statement

1014 Expected 'End'

1023 Expected expression

1015 Expected 'Function'

1010 Expected identifier

1012 Expected 'If'

1046 Expected 'In'

1026 Expected integer constant


1049 Expected Let or Set or Get in property declaration

1045 Expected literal constant

1019 Expected 'Loop'

1020 Expected 'Next'


1050 Expected 'Property'

1022 Expected 'Select'

1024 Expected statement

1016 Expected 'Sub'


VB Script For QTP 35

1017 Expected 'Then'

1013 Expected 'To'

1018 Expected 'Wend'

1027 Expected 'While' or 'Until'


1028 Expected 'While,' 'Until,' or end of statement

1029 Expected 'With'

1030 Identifier too long

1014 Invalid character


1039 Invalid 'exit' statement

1040 Invalid 'for' loop control variable

1013 Invalid number

1037 Invalid use of 'Me' keyword

1038 'loop' without 'do'

1048 Must be defined inside a Class


1042 Must be first statement on the line

1041 Name redefined

1051 Number of arguments must be consistent across properties specification

1001 Out of Memory

1054 Property Set or Let must have at least one argument


1002 Syntax error
1055 Unexpected 'Next'

1015 Unterminated string constant


For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 36

VB Script Functions

Built-In Functions of VB Script

o Conversions (25)

o Dates/Times (19)

o Formatting Strings (4)

o Input/Output (3)

o Math (9)

o Miscellaneous (3)

o Rounding (5)

o Strings (30)

o Variants (8)
Important Functions

1) Abs Function

Returns the absolute value of a number.

Dim num
num=abs(-50.33)
msgbox num

2) Array Function

Returns a variant containing an Array

Dim A

A=Array("hyderabad","chennai","mumbai")

msgbox A(0)

ReDim A(5)

A(4)="nellore"
msgbox A(4)

3) Asc Function

Returns the ANSI character code corresponding to the first letter in a string.
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 37

Dim num
num=Asc("A")
msgbox num

* It returns the value 65 *

4) Chr Function

Returns the character associated with the specified ANSI character code.

Dim char
Char=Chr(65)
msgbox char
* It returns A *

5) CInt Function

Returns an expression that has been converted to a Variant of subtype Integer.

Dim num
num=123.45
myInt=CInt(num)
msgbox MyInt

6) Date Function

Returns the Current System Date.

Dim mydate
mydate=Date
msgbox mydate

7) Day Function

Ex1) Dim myday


myday=Day("17,December,2009")
msgbox myday

Ex2) Dim myday


mydate=date
myday=Day(Mydate)
msgbox myday

8) DateDiff Function

Returns the number of intervals between two dates.

Dim myday mydate=#02-17-


2009#
x=Datediff("d",mydate,Now)
msgbox x
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 38

9) Hour Function

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

Dim mytime, Myhour


mytime=Now
myhour=hour (mytime)
msgbox myhour

10) Join Function

Returns a string created by joining a number of substrings contained in an array.

Dim mystring, myarray(3)


myarray(0)="Chandra "
myarray(1)="Mohan "
myarray(2)="Reddy"
mystring=Join(MyArray)
msgbox mystring

11) Eval Function

Evaluates an expression and returns the result.

12) Time Function

Returns a Variant of subtype Date indicating the current system time.


Dim mytime
mytime=Time
msgbox mytime

13) VarType Function

Returns a value indicating the subtype of a variable.

Dim MyCheck

MyCheck = VarType(300) ' Returns 2.

Msgbox Mycheck

MyCheck = VarType(#10/19/62#) ' Returns 7.

Msgbox Mycheck
MyCheck = VarType("VBScript") ' Returns 8.

Msgbox Mycheck

14) Left Function

Dim MyString, LeftString


MyString = "VBSCript"

LeftString = Left(MyString, 3) ' LeftString contains "VBS".


For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 39

14)Right Function

Dim AnyString, MyStr

AnyString = "Hello World" ' Define string.


MyStr = Right(AnyString, 1) ' Returns "d".

MyStr = Right(AnyString, 6) ' Returns " World". MyStr =


Right(AnyString, 20) ' Returns "Hello World".

15)Len Function

Returns the number of characters in a string or the number of bytes required


to store a variable.

Ex 1):

Dim Mystring
mystring=Len("G.C.Reddy")
msgbox mystring

Ex 2):

Dim Mystring

Mystring=Inputbox("Enter a Value")

Mystring=Len(Mystring)
Msgbox Mystring

16) Mid Function


Returns a specified number of characters from a string.

Dim MyVar

MyVar = Mid("VB Script is fun!", 4, 6)

Msgbox MyVar

* It Returns ‘Script’ *

17) Timer Function

Returns the number of seconds that have elapsed since 12:00 AM (midnight).

Function myTime(N) Dim


StartTime, EndTime

StartTime = Timer
For I = 1 To N

Next

EndTime = Timer

myTime= EndTime - StartTime


msgbox myTime

End Function

Call myTime(2000)

17) isNumeric Function

Dim MyVar, MyCheck


For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 40

MyVar = 53

MyCheck = IsNumeric(MyVar)
msgbox MyCheck

MyVar = "459.95"

MyCheck = IsNumeric(MyVar)
msgbox MyCheck

MyVar = "45 Help"

MyCheck = IsNumeric(MyVar)
msgbox MyCheck

* It Returns True/False like Result *

18) Inputbox Function

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.

Dim Input

Input = InputBox("Enter your name")

MsgBox ("You entered: " & Input)

19) Msgbox Function

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

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

20) CreateObject

creates and returns reference of the filesytemobject to an Automation object.


It can be used for performing operations on computer file system

Set objFso=createobject ("Scripting.FileSystemObject")

'creates and returns reference of the Excel bject to an Automation object. It can
be used for performing operations on Spreed sheet (Ms-Excel files)

Set objExcel = CreateObject("Excel.Application")

'creates and returns reference of the Word Object to an Automation object. It can
be used for performing operations on Ms-Word documents

Set objWord = CreateObject("Word.Application")

'creates and returns reference of the Database Connection to an Automation


object. It can be used for Connecting, opening and Closing databases
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 41

Set objConnection = CreateObject("ADODB.Connection")

'creates and returns reference of the Database Recordset to an Automation


object. It can be used for performing operations on database tables(Records)

Set objRecordSet = CreateObject("ADODB.Recordset")

'creates and returns reference of the Ms-Power point object to an Automation


object. It can be used for performing operations on Power point presentations

Set objPPT = CreateObject("PowerPoint.Application")

Set xmldoc = WScript.CreateObject("msxml2.domdocument")

21) Round

Returns a number rounded to a specified number of decimal places.

Dim num
num=172.499
num=Round(num)
msgbox num

22) StrReverse
It returns reverse value of the given sring
x=strreverse ("dabaraedyh")
msgbox x

23) strComp

It compares two strings based on ASCII Values and Returens -1 (1st less than
2nd ), 0 (Equal) and 1 (1st greater than 2nd)

Dim x, y
x="cd": y="bcd"

comp=strcomp(x,y)
msgbox comp

24) Replace

It replace a sub string with given value (another sub string)


mystring=Replace("kb script", "k","v")

msgbox mystring

For More Functions visit:

Conversion Functions
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 42

) Asc Function

Returns the ANSI character code corresponding to the first letter in a


string. Syntax:

Asc(string)

Remarks

The string argument is any valid string expression. If the string contains no
characters, a run-time error occurs.

Dim MyNumber
MyNumber = Asc("A") ' Returns 65.
MyNumber = Asc("a") ' Returns 97.
MyNumber = ' Returns
Asc("Apple") 65.

2) CByte Function

Returns an expression that has been converted to a Variant of subtype Byte.

Syntax:

CByte(expression)

The expression argument is any valid expression.

Use the CByte function to provide conversions from any data type to a Byte

subtype.
Example:

Dim MyDouble, MyByte

MyDouble = 125.5678 ' MyDouble is a Double.

MyByte = CByte(MyDouble) ' MyByte contains 126.

3) CDate Function

Returns an expression that has been converted to a Variant of subtype Date.


Syntax:
CDate(date)

The date argument is any valid date expression.

Use the IsDate function to determine if date can be converted to a date or


time. Example:

MyDate = "October 19, 1962" ' Define date.

MyShortDate = CDate(MyDate) ' Convert to Date data type.


MyTime = "4:35:47 PM" ' Define time.

' Convert to Date data


MyShortTime = CDate(MyTime) type.

4) Chr Function

Returns the character associated with the specified ANSI character code.
Syntax:
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 43

Chr(charcode)

The charcode argument is a number that identifies a character.

Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For
example, Chr(10) returns a linefeed character.

Example:

Dim MyChar

' Returns A:
MyChar =
Chr(65)

' Returns B:
MyChar =
Chr(66)

' Returns Z:
MyChar =
Chr(90)

' Returns a:
MyChar =
Chr(97)

' Returns b:

MyChar = Chr(98)

' Returns z:
MyChar =
Chr(122)
' Returns 0:
MyChar =
Chr(48)

' Returns 1:

MyChar = Chr(49)

' Returns 9:

MyChar = Chr(57)

' Returns
horizontal tab:
MyChar = Chr(9)

' Returns >:

MyChar = Chr(62)
' Returns %:
MyChar = Chr(37)

5) CLng Function

Returns an expression that has been converted to a Variant of subtype Long.


Syntax:

CLng(expression)

The expression argument is any valid expression.

Use the CLng function to provide conversions from any data type to a
Long subtype.

Example:
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 44

Dim MyVal1, MyVal2, MyLong1, MyLong2

MyVal1 = 25427.45: MyVal2 = 25427.55 ' MyVal1, MyVal2 are Doubles.

MyLong1 = CLng(MyVal1) ' MyLong1 contains 25427.

MyLong2 = CLng(MyVal2) ' MyLong2 contains 25428.

6) CStr Function

Returns an expression that has been converted to a Variant of subtype String.

Syntax:
CStr(expression)

The expression argument is any valid expression.

Example:

Dim MyDouble, MyString


MyDouble = 437.324 ' MyDouble is a Double.

MyString = CStr(MyDouble) ' MyString contains "437.324"

7) Oct Function

Returns a string representing the octal value of a number.

Syntax:

Oct(number)
The number argument is any valid expression.

Example:

Dim MyOct

MyOct = Oct(4) ' Returns 4.

MyOct = Oct(8) ' Returns 10.

MyOct = Oct(459) ' Returns 713.

8) CBool Function

Returns an expression that has been converted to a Variant of subtype


Boolean. Synta:

CBool(expression)

The expression argument is any valid expression.

If expression is zero, False is returned; otherwise, True is returned. If expression


can't be interpreted as a numeric value, a run-time error occurs.
Example:
Dim A, B,
Check
A = 5: B = 5 ' Initialize variables.
Check = CBool(A = ' Check contains
B) True.

A=0 ' Define variable.


Check = CBool(A) ' Check contains False.
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 45

9) CCur Function

Returns an expression that has been converted to a Variant of subtype Currency.

Syntax:
CCur(expression)

The expression argument is any valid expression.


Example:
Dim MyDouble, MyCurr

MyDouble = 543.214588 ' MyDouble is a Double.

MyCurr = CCur(MyDouble * 2) ' Convert result of MyDouble * 2 (1086.429176)


to a Currency (1086.4292).

10) CInt Function

Returns an expression that has been converted to a Variant of subtype Integer.


Syntax:

CInt(expression)

The expression argument is any valid expression.


Example:

Dim MyDouble, MyInt

MyDouble = 2345.5678 ' MyDouble is a Double.


MyInt = CInt(MyDouble) ' MyInt contains 2346.

11) CSng Function

Returns an expression that has been converted to a Variant of subtype Single.

Syntax:
CSng(expression)

The expression argument is any valid expression.

Example:

Dim MyDouble1, MyDouble2, MySingle1, MySingle2 ' MyDouble1, MyDouble2

are Doubles.

MyDouble1 = 75.3421115: MyDouble2 = 75.3421555

MySingle1 = CSng(MyDouble1) ' MySingle1 contains 75.34211.

MySingle2 = CSng(MyDouble2) ' MySingle2 contains 75.34216.

12) Hex Function

Returns a string representing the hexadecimal value of a number.

Syntax:
Hex(number)

number argument is any valid expression.

we can represent hexadecimal numbers directly by preceding numbers in the


For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 46

proper range with &H.


Example:
Dim MyHex

MyHex = Hex(5) ' Returns 5.


MyHex = Hex(10) ' Returns A.

MyHex =
Hex(459) ' Returns 1CB.
VB Script For QTP 47

Regular Expressions in QTP

What is Regular Expression?

It is a way of representing data using symbols. They are often used


within matching, searching or replacing algorithms.

Regular Expressions in QTP:

Regular expressions can be used in QTP for identifying objects and text strings
with varying values.

Where we use:

o Defining the property values of an object in Descriptive programming


for handling dynamic objects

o For parameterizing a step

o creating checkpoints with varying values

Using Regular Expressions in QTP:

We can define a regular expression for a constant value, a Data Table


parameter value, an Environment parameter value, or a property value in
Descriptive programming.

We can define a regular expression in standard checkpoint to verify the property


For more QTP Realtime Sripts, visit
www.ramupalanki.com
values of an object; we can set the expected value of an object's property as a
regular expression so that an object with a varying value can be verified.

We can define the text string as a regular expression, when creating a text
checkpoint to check that a varying text string is displayed on our application,
For XML checkpoints we can set attribute or element values as regular
expressions.

Ways of Regular Expressions:

a) Backslash Character:

A backslash (\) can serve two purposes. It can be used in conjunction with
a special character to indicate that the next character be treated as a literal
character.

Alternatively, if the backslash (\) is used in conjunction with some characters that
would otherwise be treated as literal characters, such as the letters n, t, w, or d,
the combination indicates a special character.

b) Matching Any Single Character:


VB Script For QTP 48

A period (.) instructs QTP to search for any single character (except for \n).
Ex:

welcome.

Matches welcomes, welcomed, or welcome followed by a space or any other


single character.

c) Matching Any Single Character in a List:

Square brackets instruct QTP to search for any single character within a list of
characters.

Ex:
To search for the date 1867, 1868, or 1869, enter:

186[789]

d) Matching Any Single Character Not in a List:

When a caret (^) is the first character inside square brackets, it instructs QTP to
match any character in the list except for the ones specified in the string.

Example:

[^ab]

Matches any character except a or b.

e) Matching Any Single Character within a Range:

To match a single character within a range, we can use square brackets ([ ])


For more QTP Realtime Sripts, visit
www.ramupalanki.com
with the hyphen (-) character.

Example:

For matching any year in the 2010s, enter:

201[0-9]

f) Matching Zero or More Specific Characters:

An asterisk (*) instructs QTP to match zero or more occurrences of


the preceding character.

For example:

ca*r

Matches car, caaaaaar, and cr

g) Matching One or More Specific Characters:

A plus sign (+) instructs QTP to match one or more occurrences of the preceding
character.

For example:
VB Script For QTP 49

ca+r

Matches car and caaaaaar, but not cr.

h) Matching Zero or One Specific Character:

A question mark (?) instructs QTP to match zero or one occurrences of


the preceding character.

For example:
ca?r

Matches car and cr, but nothing else.

i) Grouping Regular Expressions:

Parentheses (()) instruct QTP to treat the contained sequence as a unit, just as
in mathematics and programming languages. Using groups is especially useful
for delimiting the argument(s) to an alternation operator ( | ) or a repetition
operator ( * , + , ? , { } ).

j) Matching One of Several Regular Expressions:

A vertical line (|) instructs QTP to match one of a choice of expressions.

k) Matching the Beginning of a Line:

A caret (^) instructs QTP to match the expression only at the start of a line,
or after a newline character.
For more QTP Realtime Sripts, visit
www.ramupalanki.com
l) Matching the End of a Line:

A dollar sign ($) instructs QTP to match the expression only at the end of a
line, or before a newline character.

m) Matching Any AlphaNumeric Character Including the Underscore:

\w instructs QTP to match any alphanumeric character and the underscore (A-Z,
a-z, 0-9, _).

n) Matching Any Non-AlphaNumeric Character:

\W instructs QTP to match any character other than alphanumeric


characters and underscores.

o) Combining Regular Expression Operators:

We can combine regular expression operators in a single expression to


achieve the exact search criteria we need.

For example,
VB Script For QTP 50

start.*

Matches start, started, starting, starter, and so forth.

we can use a combination of brackets and an asterisk to limit the search to


a combination of non-numeric characters.
For example:
[a-zA-Z]*

To match any number between 0 and 1200, we need to match numbers with 1
digit, 2 digits, 3 digits, or 4 digits between 1000-1200.
The regular expression below matches any number between 0 and
1200. ([0-9]?[0-9]?[0-9]|1[01][0-9][0-9]|1200)

RegExp object

VB Script is providing RegExp object for defining Regular expressions,


It provides simple support for defining regular expressions.

Regular Expression Object Properties and Methods:

Properties:

a) Global Property

b) IgnoreCase Property

c) Pattern Property

Methods:
For more QTP Realtime Sripts, visit
www.ramupalanki.com

a) Execute Method

b) Replace Method

c) Test Method

Regular Expressions Examples:

1) Match File Names in a Directory against Regular Expression

Set objFS = CreateObject("Scripting.FileSystemObject")


Set objShell = CreateObject("WScript.Shell")
strCurrentDirectory = objShell.CurrentDirectory

Set objFolder = objFS.GetFolder(strCurrentDirectory)

Set colFiles = objFolder.Files

Set objRE = New RegExp


objRE.Global = True
objRE.IgnoreCase = False
VB Script For QTP 51

objRE.Pattern = WScript.Arguments(0)

For Each objFile In colFiles

bMatch = objRE.Test(objFile.Name)

If bMatch Then WScript.Echo


objFile.Name

End
If Next

2) Match Content in a File against a Regular Expression


strFileName = "E:\gcreddy.txt"

Set objFS = CreateObject("Scripting.FileSystemObject")

Set objTS = objFS.OpenTextFile(strFileName)


strFileContents = objTS.ReadAll

WScript.Echo "Searching Within: "


WScript.Echo strFileContents
objTS.Close

Set objRE = New RegExp


objRE.Global = True
objRE.IgnoreCase = False

objRE.Pattern = WScript.Arguments(0)

Set colMatches = objRE.Execute(strFileContents)

WScript.Echo vbNewLine & "Resulting Matches:"


For Each objMatch In colMatches
WScript.Echo "At position " & objMatch.FirstIndex & " matched "
For more QTP Realtime Sripts, visit
www.ramupalanki.com
& objMatch.Value

Next
VB Script For QTP 52

VB Script Objects

a) FileSystemObject

Scripting allows us to process drives, folders, and files using


the FileSystemObject (FSO) object model.

Creating FileSystemObject:

Set Variable=CreateObject("Scripting.FileSystemObject")

Example:

Dim objFso

Set objFso=CreateObject("Scripting.FileSystemObject")
objFso.CteateTextFile("D:\gcreddy.txt")

b) Dictionary

Creating Dictionary Object:

Set Variable=CreateObject("Scripting.Dictionary")

Example:
For more QTP Realtime Sripts, visit
www.ramupalanki.com
c) Excel Application

Creating Excel Object:

Set Variable=CreateObject("Excel.Application")

Example:

d) Word Application

Creating Word Object:

Set Variable=CreateObject("Word.Application")

Example:

e) Shell

Creating Shell Object:

Set Variable= WScript.CreateObject("Wscript.Shell")

Example:
VB Script For QTP 53

f) Network

Creating Network Object:

Set Variable= WScript.CreateObject("WScript.Network")

Example:

g) PowerPoint

Creating PowerPointObject:

Set Variable=CreateObject("PowerPoint.Application")

Example:

h) ADODB Connection

The ADO Connection Object is used to create an open connection to a data


source. Through this connection, you can access and manipulate a database.
For more QTP Realtime Sripts, visit
www.ramupalanki.com
Creating Database Connection Object:

Set Variable=CreateObject("ADODB.Connection")

Example:

i) ADODB RecordSet

The ADO Recordset object is used to hold a set of records from a


database table. A Recordset object consist of records and columns (fields).

Creating Database RecordSet Object:

Set Variable=CreateObject("ADODB.RecordSet")

Example:

j) ADODB Command

The ADO Command object is used to execute a single query against a


database. The query can perform actions like creating, adding, retrieving,
deleting or updating records.
VB Script For QTP 54

Creating Database Command Object:

Set Variable=CreateObject("ADODB.Command")

Example:

k) Error

Creating Error Object:

l) RegExp

Creating RegExp Object:

Set objReg=CreateObject("vbscript.regexp")

m) Internet Explorer

n) Outlook Express
For more QTP Realtime Sripts, visit
www.ramupalanki.com

a) Dictionary Object

Dictionary Object that stores data key, item pairs.

A Dictionary object is the equivalent of a PERL associative array/Hash Variable.

Items can be any form of data, and are stored in the array. Each item is
associated with a unique key. The key is used to retrieve an individual item
and is usually an integer or a string, but can be anything except an array.

Creating a Dictionary Object:

Set objDictionary = CreateObject("Scripting.Dictionary")

Dictionary Objects Methods:

Add Method

Adds a key and item pair to a Dictionary object


VB Script For QTP 55

Exists Method

Returns true if a specified key exists in the Dictionary object, false if it does not.

Items Method

Returns an array containing all the items in a Dictionary object.

Keys Method

Returns an array containing all existing keys in a Dictionary object.

Remove Method

Removes a key, item pair from a Dictionary object.

RemoveAll Method

The RemoveAll method removes all key, item pairs from a Dictionary object.

Example:

Dim cities
For more QTP Realtime Sripts, visit
www.ramupalanki.com
Set cities = CreateObject("Scripting.Dictionary")
cities.Add "h", "Hyderabad"

cities.Add "b", "Bangalore"


cities.Add "c", "Chennai"

Dictionary Objects Properties:

Count Property

Returns the number of items in a collection or Dictionary object. Read-only.

CompareMode Property

Sets and returns the comparison mode for comparing string keys in a
Dictionary object.

Key Property

Sets a key in a Dictionary object.

Item Property

Sets or returns an item for a specified key in a Dictionary object. For


collections, returns an item based on the specified key. Read/write.
VB Script For QTP 56

Examples:

a to Elements 1) AddDictionary

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"


objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"

a 2) Delete All Elements fromDictionary

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"


objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
colKeys = objDictionary.Keys

Wscript.Echo "First run: "

For Each strKey in colKeys


For more QTP Realtime Sripts, visit
www.ramupalanki.com
Wscript.Echo strKey

Next

objDictionary.RemoveAll
colKeys = objDictionary.Keys

Wscript.Echo VbCrLf & "Second run: "

For Each strKey in colKeys

Wscript.Echo strKey

Next

3) Delete One Element from a Dictionary

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"


objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"

colKeys = objDictionary.Keys
VB Script For QTP 57

Wscript.Echo "First run: "

For Each strKey in colKeys

Wscript.Echo strKey
Next

objDictionary.Remove("Printer
2") colKeys = objDictionary.Keys

Wscript.Echo VbCrLf & "Second run: "

For Each strKey in colKeys

Wscript.Echo strKey

Next

4) List the Number of Items in a Dictionary

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"


objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
Wscript.Echo objDictionary.Count
For more QTP Realtime Sripts, visit
www.ramupalanki.com
5) Verify the Existence of a Dictionary Key

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"


objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"

If objDictionary.Exists("Printer 4") Then

Wscript.Echo "Printer 4 is in the Dictionary."

Else

Wscript.Echo "Printer 4 is not in the Dictionary."

End If
VB Script For QTP 58

VBScript Coding Conventions

Coding conventions are suggestions are designed to help us write code using
VB Script.

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
we and others can easily read and understand the code.

Using good coding conventions results in clear, precise, and readable source
code that is consistent with other language conventions and is intuitive.

Variable Naming Conventions

To enhance readability and consistency, we have to use the following prefixes


with descriptive names for variables in our VBScript code.

Subtype Prefix Example


----------------------------------------------
Boolean bln blnFound
For more QTP Realtime Sripts, visit
www.ramupalanki.com

-----------------------------------------------
bytRasterDat
Byte byt a

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


-----------------------------------------------------

Object Naming Conventions:


VB Script For QTP 59

The following table lists recommended conventions for objects you may
encounter while programming VBScript.

Object type Prefix Example


---------------------------------------------------
3D Panel pnl pnlGroup

---------------------------------------------------
Animated
button ani aniMailBox

---------------------------------------------------
chkReadOnl
Check box chk y

---------------------------------------------------
Combo box cbo cboEnglish

---------------------------------------------------
Command
button cmd cmdExit
---------------------------------------------------
Common dialog dlg dlgFileOpen

---------------------------------------------------
Frame fra fraLanguage

---------------------------------------------------

Image img imgIcon


---------------------------------------------------

lblHelpMessag
Label lbl e
---------------------------------------------------
For more QTP Realtime Sripts, visit
www.ramupalanki.com

Line lin linVertical


---------------------------------------------------

List Box lst lstPolicyCodes


---------------------------------------------------

Spin spn spnPages


---------------------------------------------------

Text box txt txtLastName


---------------------------------------------------

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, 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
VB Script For QTP 60

range. Return values for functions and variables that are changed by a
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 "Formatting Your Code" section that follows.

Section Heading Comment Contents

Purpose: What the procedure does (not how).

Assumptions: List of any external variable, control, or otherelement


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 is not 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 to ensure


For more QTP Realtime Sripts, visit
www.ramupalanki.com
that inline comments are only needed for complex implementation details.

•At the beginning of your script, you should include an overview that describes
the script, enumerating objects, procedures, algorithms, dialog boxes, and
other system dependencies. Sometimes a piece of pseudocode describing the
algorithm can be helpful.

Formatting the 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 suggestions:

• Indent standard nested blocks four spaces.

• Indent the overview comments of a procedure one space.

• Indent the highest level statements that follow the overview comments
four spaces, with each nested block indented an additional four
spaces.
VB Script For QTP 61

The following code adheres to VBScript coding conventions.


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

' Purpose: Locates the first occurrence of a specified user

' in the UserList array.

' Inputs: strUserList(): the list of users to be searched.

' strTargetUser: the name of the user to search for.

' Returns: The index of the first occurrence of the strTargetUser

' in the strUserList array.

' If the target user is not found, return -1.


'***************************************************
****** Function intFindUser (strUserList(),
strTargetUser)

Dim i ' Loop counter.

Dim blnFound ' Target found flag


intFindUser = -1
i = 0 ' Initialize loop counter

Do While i <= Ubound(strUserList) and Not blnFound


If strUserList(i) = strTargetUser Then
blnFound = True ' Set flag to True intFindUser
= i ' Set return value to loop count

End If

i = i + 1 ' Increment loop counter


Loop

End Function
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 62

VB Script Classes

Creating Classes

Classes aren't a new concept in scripting. JavaScript, JScript, and other


scripting languages have supported classes or similar elements for years.
However, VBScript 5.0 is the first version of VBScript to support classes.

To use classes in your VBScript code, you first need to obtain VBScript 5.0 by
downloading the appropriate self-executable file from the Microsoft Developer
Network (MSDN) Web site (http://msdn.microsoft.com/scripting) or by
installing Microsoft Internet Explorer (IE) 5.0. Then you need to understand
what a VBScript class is and learn how to declare, define, initialize, and
instantiate a class.

VBScript Classes

VBScript 5.0 supports two types of objects: COM objects and Class objects

(typically referred to as simply classes). VBScript COM objects have basic


subtypes, such as an Integer or String. VBScript classes have an abstract
subtype that encapsulates data and the functions to work with that data. You
can think of a VBScript class as having a souped-up subtype that provides you
with more computing power and flexibility. (Other differences exist between
these two types of objects. For more information, see the Web-exclusive sidebar
"How VBScript Classes and COM Objects Differ" on the Win32 Scripting Journal
Web site at http://www.winntmag.com/ newsletter/scripting.

You can use classes to describe complex data structures. For example, if your
application tracks customers and orders, you can define two classes for them,
each with a unique set of internal data (typically called properties) and functions
(typically called methods). You can then manage customers and orders as if they
were native VBScript subtypes. More important, because you assign a class its
properties and methods (i.e., its programming interface), you have an object-
oriented tool to improve VBScript applications.

Declaring a Class

You use the Class statement to declare a class. This statement's syntax is:

Class name

' Properties and methods go here.


End Class

where name is the name you give that class. You declare the properties
and methods for your class between the Class and End Class clauses.

For example, suppose you want to create the VBScript class FileList, which
Listing 1 contains. This class manages those files in a folder that meet a filename
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 63

specification that you provide. You create this class by first specifying the
keyword Class followed by the class' name Class FileList. Next, you declare
the class' properties and methods. FileList has two properties (FileSpec and
FolderPath) and one method (Search).

Declaring the FileSpec Property

The FileSpec property holds the filename specification. For example, the
filename specification might be C:\*.*. You want users to be able to freely
read and write values to this property, so you declare FileSpec as an external,
or public, variable with the Public statement

Public FileSpec

You can use a public variable in any script, not just the script in which you
created the variable. However, if you use a public variable, you have no control
over the value that users assign to the variable and no control over the value that
the variable returns. Thus, you can't use public variables to hold values that you
need to validate.

Declaring the FolderPath Property

The FolderPath property holds the full path to the folder containing the files. After
a user sets a folder path, you need to validate that the folder exists, which
means you can't use a public variable. Instead, you need to store the folder path
in an internal, or private, variable and use two public property procedures to read
and write to that variable. (Public property procedures are wrappers that hide the
code that gets and sets the values of private variables.)

Prefixing a private variable with the m_ string is a common scripting convention.


For example, the private variable for the FolderPath property is m_folderPath. To
declare m_folderPath, you use the Private statement

Private m_folderPath

Procedures and variables that have the Private qualifier aren't visible outside the
class. In addition, private variables apply only to the script in which you created
them.

After you declare m_folderPath, you need to declare the two public property
procedures that you'll use to read and write to that variable. The first procedure to
declare is the Property Get procedure, which returns the values of properties.

The second procedure is the Property Let procedure, which assigns values to
properties.

To declare the Property Get procedure, you use the Property Get statement
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 64

Public Property Get FolderPath

FolderPath =
m_folderPath End Property
where FolderPath is the name of that procedure. By including the Public
statement with the Property Get statement, you're making the value that the

FolderPath procedure returns available for public reading. Thus, by assigning


FolderPath to m_folderPath, you make the value of m_folderPath available for
public reading.
VB Script For QTP 65

VBScript Syntax Rules and Guidelines

1) Case-sensitivity:

By default, VBScript is not case sensitive and does not differentiate between
upper-case and lower-case spelling of words, for example, in variables, object
and method names, or constants.

For example, the two statements below are identical in VBScript:

Browser("Mercury").Page("Find a Flight:").WebList("toDay").Select "31"


browser("mercury").page("find a flight:").weblist("today").select "31"

2) Text strings:

When we enter a value as a text string, we must add quotation marks before and
after the string. For example, in the above segment of script, the names of the

Web site, Web page, and edit box are all text strings surrounded by
quotation marks.

Note that the value 31 is also surrounded by quotation marks, because it is a text
string that represents a number and not a numeric value.

In the following example, only the property name (first argument) is a text
string and is in quotation marks. The second argument (the value of the
property) is a variable and therefore does not have quotation marks. The third
argument (specifying the timeout) is a numeric value, which also does not
need quotation marks.
For more QTP Realtime Sripts, visit
www.ramupalanki.com
Browser("Mercury").Page("Find a Flight:").WaitProperty("items
count", Total_Items, 2000)

3) Variables:

We can specify variables to store strings, integers, arrays and objects.


Using variables helps to make our script more readable and flexible

4) Parentheses:

To achieve the desired result and to avoid errors, it is important that we use
parentheses () correctly in our statements.

5) Indentation:

We can indent or outdent our script to reflect the logical structure and nesting
of the statements.
VB Script For QTP 66

6) Comments:

We can add comments to our statements using an apostrophe ('), either at the
beginning of a separate line, or at the end of a statement. It is recommended
that we add comments wherever possible, to make our scripts easier to
understand and maintain.

7) Spaces:

We can add extra blank spaces to our script to improve clarity. These spaces
are ignored by VBScript
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 67

VB Script Examples

VB Script General Examples

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

Dim xyear

xyear=inputbox ("Enter Year")


If xyear mod 4=0 Then
msgbox "This is a Leap year"
Else

msgbox "This is
NOT" End If

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

Dim num

num=inputbox ("Enter a number")

If num mod 2=0 Then

msgbox "This is a Even


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

3) Read two numbers and display the sum?

Dim num1,num2, sum


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

sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require
msgbox ("Sum is " &sum)

4) Read P,T,R values and Calculate the Simple Interest?

Dim p,t, r, si

p=inputbox ("Enter Principle")


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

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


interest msgbox ("Simple Interest is " &si)

5) Read Four digit number, calculate & display the sum of the number
or display Error message if the number is not a four digit number?
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 68

Dim num, sum

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

If Len(num) = 4
Then sum=0
sum=sum+num mod
10 num=num/10

num= left (num, 3)


sum=sum+num mod
10 num=num/10

num= left (num, 2)


sum=sum+num mod
10 num=num/10

num= left (num, 1)


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

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

End If

6) Read any Four-digit number and display the number in reverse order?

Dim num,rev

num= inputbox("Enter a
number") If len(num)=4 Then
rev=rev*10 + num mod 10
num=num/10

num= left(num,3)
rev=rev*10 + num mod 10
num=num/10

num= left(num,2)
rev=rev*10 + num mod 10
num=num/10

num= left(num,1)
rev=rev*10 + num mod 10

msgbox "Reverse Order of the number is "&rev

Else

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

End If

7) Read 4 subjects marks; calculate the Total marks and grade?

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 , then


grade is First

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


grade is Second
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 69

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


grade is Third

e) Minimum marks 35 for any subject, otherwise 'no grade fail')

Dim e,m,p,c, tot

e=inputbox ("Enter english Marks")


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

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

msgbox "Grade is Distinction"


else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot

>=240 and tot<300 Then


msgbox "Grade is First"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot

>=200 and tot<240 Then


msgbox "Grade is Second"

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

msgbox "Grade is Third"


else

msgbox "No Grade, Fail"


End If

End If

End If

End If

8) Display Odd numbers up to n?

Dim num,n

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

Next

9) Display Even numbers up to n?

Dim num,n

n=Inputbox ("Enter a Vaule")

For num= 2 to n step


2 msgbox num

Next
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 70

10) display natural numbers up to n and write in a text file?

Dim num, n, fso, myfile

n= inputbox ("Enter any Value")


num=1

For num= 1 to n step 1

Set fso= createobject ("scripting.filesystemobject")


set myfile=fso.opentextfile ("E:\gcreddy.txt", 8,
true) myfile.writeline num

myfile.close
Next

11) Display Natural numbers in reverse order up to n?

Dim num,n

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

Next

12) Display Natural numbers sum up to n? (Using For...Next Loop)

Dim num, n, sum

n= inputbox ("Enter a Value")


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

13) Display Natural numbers sum up to n? (using While...Wend Loop)

Dim num, n, sum

n= inputbox ("Enter a Value")


While num <=cdbl (n)

sum= sum+num
num=num+1

Wend
msgbox sum

14) Display Natural numbers sum up to n? (Using Do...Until...Loop)

Dim num, n, sum

n= inputbox ("Enter a Value")


sum=0

num=1
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 71

Do

sum= sum+num
num=num+1

Loop Until num =cdbl (n+1)


msgbox sum

15) Write a Function for Natural Numbers sum up to n?

Function NNumCou (n)


Dim num, sum

sum=0

For num= 1 to n step


1 sum= sum+num
Next msgbox
sum

End Function

16) Verify weather the entered 10 digit value is a numeric value or not?

Dim a,x,y,z,num

num=Inputbox ("Enter a Phone


Number") d1= left (num,1)

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

If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True"
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 (d10) = "True" Then

msgbox "It is a Numeric Value"


else

Msgbox "It is NOT


Numeric" End If

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

Dim a,x,y,z,num
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 72

num=Inputbox ("Enter a Phone


Number") d1= left (num,1)

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

If len (num) =10 Then

If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) =

"True" 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 (d10) = "True" Then


msgbox "It is a Numeric Value"

End If

End If

If len (num) <> 10 Then

Msgbox "It is NOT valid Number "

End If
18) Generate interest for 1 to 5 years (for 1 year -7%, 2 years -8%, 3 years-
9%, 4 years-10%, 5 years -11%)

Dim amount, duration, intr


amount=inputbox("enter amount")
If amount<10000 Then

msgbox "low
amount" else

For duration=1 to 5
If duration=1 Then
intr=amount*7/100

msgbox "1 year intrest is: " &intr

else if duration=2 Then


intr=amount*8/100

msgbox "2 years intrest is: " &intr

else if duration=3 Then


intr=amount*9/100

msgbox "3 years intrest is: "&intr

else if duration=4 Then


For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 73

intr=amount*10/100

msgbox "4 years intrest is: "&intr

else if duration=5 Then


intr=amount*11/100

msgbox "5 years intrest is: "&intr


else
msgbox "invalid data"
End If

End If

End If

End If

End If

Next
End If

For More Examples:

VB Script Examples-II

VB Script General Examples


1) Read a value and find size of the value

Dim val: val=Inputbox("Enter value for val: ")


val_length =Len(val)

msgbox "Size of "&val&" is "&val_length

2) Read a value and find whether the value is numeric or not?

Dim val: val=Inputbox("Enter value for val: ")


val_type =IsNumeric(val)

If val_type = true Then


msgbox "val is Numeric"

else

msgbox "val is not Numeric"


End If

3)'Read a value and find whether the value is Date type data or not?

Dim val: val=Inputbox("Enter value for val: ")


val_type =IsDate(val)

If val_type = true Then

msgbox "val is Date type


data" else

msgbox "val is not date type"


For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 74

End If

4)Read a value and Verify whether the value is 10-digit number or not and
started with 9 0r 8.

'Then Display it is a valid mobile number

Dim val,val_Length, val_Numeric, val_Start


val=Inputbox("Enter value for val: ")
val_Length= Len(val)
val_Numeric=IsNumeric(val)
val_Start=Left(val,1)

If val_Length=10 and val_Numeric and val_Start=9 or val_Start=8 Then


msgbox val&" is a valid mobile number "

Else

msgbox val&" is not a valid mobile number "

End If

5) 'Read a mobile number and verify the series

'if it starts with 92478 or 92471 then display it is TataIndicom number 'if
it starts with 98490 or 98480 then display it is Airtel number

Dim val, val_Length,val_Numeric,val_Series,val_Start


val=Inputbox("Enter value for val: ")
val_Length= Len(val)
val_Numeric=IsNumeric(val)
val_Start=Left(val,1)
val_Series=Left(val,5)

If val_Numeric=true Then

If val_Length=10 and val_Start=9 Then

If val_Series = 92478 or val_Series=92471


Then msgbox "It is TataIndicom Number"

ElseIf val_Series=98490 or val_Series = 98480


then msgbox "It is Airtel Number"
End If

Else

msgbox val&" is not a valid mobile number "

End If

Else

msgbox val& " is Invalid data"

End If
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 75

6) Read a Value and Verify weather the value is started with Alfa bytes
or not? (First letter should be Alfa byte)

Dim val, val_Asc

val=Inputbox("enter a
value") val_Asc=Asc(val)

Msgbox val_Asc

If val_Asc>=65 and val_Asc<=90 or val_Asc>=97 and val_Asc<=122Then


msgbox val&" is an Alphabet"

Else

msgbox val&" is not an


Alphabet" End If

7) Read a value and Verify weather the value is Alfa bytes are not?

Dim str, valAsc, flag,i

Dim strlen, counter,valsingle


counter=0

str=Inputbox("enter a string value")


strlen= Len(str)

For i=1 to strlen step 1


valsingle=Mid(str,i,1)
valAsc=Asc(valsingle)

If valAsc>=65 and valAsc<=90 or valAsc>=97 and


valAsc<=122Then flag=1

counter=counter+1

Else
flag=0
End If

Next

msgbox "No.of characters " &counter

If counter=strlen and flag=1Then


msgbox str&" is an Alphabetic value"

Else

msgbox str&" is not an Alphabetic value"


End If
For more QTP Realtime Sripts, visit
www.ramupalanki.com
VB Script For QTP 76
VB Script For QTP 77

VB Script Glossary of Terms

ActiveX control

An object that you place on a form to enable or enhance a user's interaction with
an application. ActiveX controls have events and can be incorporated into other
controls. The controls have an .ocx file name extension.

ActiveX object

An object that is exposed to other applications or programming tools through


Automation interfaces.

Argument

A constant, variable, or expression passed to a procedure.

Array

A set of sequentially indexed elements having the same type of data. Each
element of an array has a unique identifying index number. Changes made
to one element of an array do not affect the other elements.

ASCII Character Set

American Standard Code for Information Interchange (ASCII) 7-bit character set
widely used to represent letters and symbols found on a standard U.S.
keyboard. The ASCII character set is the same as the first 128 characters (0–
127) in the ANSI character set.

Automation object
For more QTP Realtime Sripts, visit
www.ramupalanki.com
An object that is exposed to other applications or programming tools through

Automation interfaces.

Bitwise comparison

A bit-by-bit comparison of identically positioned bits in two numeric expressions.

Boolean expression

An expression that evaluates to either True or False.

By reference

A way of passing the address, rather than the value, of an argument to a


procedure. This allows the procedure to access the actual variable. As a result,
the variable's actual value can be changed by the procedure to which it is
passed.

By value

A way of passing the value, rather than the address, of an argument to a


procedure. This allows the procedure to access a copy of the variable. As a
result, the variable's actual value can't be changed by the procedure to which it
is passed.
VB Script For QTP 78

character code

A number that represents a particular character in a set, such as the


ASCII character set.

Class

The formal definition of an object. The class acts as the template from which an
instance of an object is created at run time. The class defines the properties of
the object and the methods used to control the object's behavior.

Class module

A module containing the definition of a class (its property and


method definitions).

Collection

An object that contains a set of related objects. An object's position in the


collection can change whenever a change occurs in the collection; therefore,
the position of any specific object in the collection may vary.

Comment

Text added to code by a programmer that explains how the code works. In
Visual Basic Scripting Edition, a comment line generally starts with an
apostrophe ('), or you can use the keyword Rem followed by a space.

Comparison operator

A character or symbol indicating a relationship between two or more values or


For more QTP Realtime Sripts, visit
www.ramupalanki.com
expressions. These operators include less than (<), less than or equal to (<=),
greater than (>), greater than or equal to (>=), not equal (<>), and equal (=).

Is is also a comparison operator, but it is used exclusively for determining if


one object reference is the same as another.

Constant

A named item that retains a constant value throughout the execution of a


program. Constants can be used anywhere in your code in place of actual
values. A constant can be a string or numeric literal, another constant, or
any combination that includes arithmetic or logical operators except Is and
exponentiation. For example:

Data ranges

Each Variant subtype has a specific range of allowed values:


Subtype Range

Byte 0 to 255. Boolean


True or False.

Integer -32,768 to 32,767.

Long -2,147,483,648 to 2,147,483,647.

Single -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to


VB Script For QTP 79

3.402823E38 for positive values.

Double -1.79769313486232E308 to -4.94065645841247E-324 for negative


values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.

Date January 1, 100 to December 31, 9999,


inclusive. Object Any Object reference.

String Variable-length strings may range in length from 0 to approximately 2


billion characters.

Date expression

Any expression that can be interpreted as a date. This includes any combination of
date literals, numbers that look like dates, strings that look like dates, and dates
returned from functions. A date expression is limited to numbers or strings, in any
combination, that can represent a date from January 1, 100 through

December 31, 9999.

Dates are stored as part of a real number. Values to the left of the decimal
represent the date; values to the right of the decimal represent the time. Negative
numbers represent dates prior to December 30, 1899.

Date literal

Any sequence of characters with a valid format that is surrounded by number


signs (#). Valid formats include the date format specified by the locale settings for
your code or the universal date format. For example, #12/31/99# is the date
literal that represents December 31, 1999, where English-U.S. is the locale
setting for your application.
For more QTP Realtime Sripts, visit
www.ramupalanki.com
In VBScript, the only recognized format is US-ENGLISH, regardless of the
actual locale of the user. That is, the interpreted format is mm/dd/yyyy.

Date separators

Characters used to separate the day, month, and year when date values are
formatted.

Empty

A value that indicates that no beginning value has been assigned to a variable.
Empty variables are 0 in a numeric context, or zero-length in a string context.

Error number

A whole number in the range 0 to 65,535, inclusive, that corresponds to the


Number property of the Err object. When combined with the Name property
of the Err object, this number represents a particular error message.
VB Script For QTP 80

Expression

A combination of keywords, operators, variables, and constants that yield a


string, number, or object. An expression can perform a calculation, manipulate
characters, or test data.

Intrinsic constant

A constant provided by an application. Because you can't disable intrinsic


constants, you can't create a user-defined constant with the same name.

Keyword

A word or symbol recognized as part of the VBScript language; for example, a


statement, function name, or operator.

Locale

The set of information that corresponds to a given language and country. A


locale affects the language of predefined programming terms and locale-specific
settings. There are two contexts where locale information is important:

• The code locale affects the language of terms such as keywords and
defines locale-specific settings such as the decimal and list separators,
date formats, and character sorting order.

• The system locale affects the way locale-aware functionality behaves, for
example, when you display numbers or convert strings to dates. You set the
system locale using the Control Panel utilities provided by the operating
system.
For more QTP Realtime Sripts, visit
www.ramupalanki.com
Nothing

The special value that indicates that an object variable is no longer


associated with any actual object.

Null

A value indicating that a variable contains no valid data. Null is the result of:

• An explicit assignment of Null to a variable.

• Any operation between expressions that contain Null.

Numeric expression

Any expression that can be evaluated as a number. Elements of the expression


can include any combination of keywords, variables, constants, and operators
that result in a number.

Object type

A type of object exposed by an application, for example, Application, File, Range,


and Sheet. Refer to the application's documentation (Microsoft Excel, Microsoft
VB Script For QTP 81

Project, Microsoft Word, and so on) for a complete listing of available objects.

pi

Pi is a mathematical constant equal to approximately 3.1415926535897932.

Private

Variables that are visible only to the script in which they are declared.

Procedure

A named sequence of statements executed as a unit. For example, Function and


Sub are types of procedures.

Procedure level

Describes statements located within a Function or Sub procedure.


Declarations are usually listed first, followed by assignments and other
executable code. For example:

Sub MySub() ' This statement declares a sub procedure block.

Dim A ' This statement starts the procedure


block. A = "My variable" ' Procedure-level code.
Debug.Print A ' Procedure-level code.
For more QTP Realtime Sripts, visit
www.ramupalanki.com
End Sub ' This statement ends a sub procedure block.
Note that script-level code resides outside any procedure blocks.

Property

A named attribute of an object. Properties define object characteristics such


as size, color, and screen location, or the state of an object, such as enabled
or disabled.

Public

Variables declared using the Public Statement are visible to all procedures in all
modules in all applications.

Run time

The time when code is running. During run time, you can't edit the code.

Run-time error

An error that occurs when code is running. A run-time error results when
a statement attempts an invalid operation.
VB Script For QTP 82

Scope

Defines the visibility of a variable, procedure, or object. For example, a variable


declared as Public is visible to all procedures in all modules. Variables declared
in procedures are visible only within the procedure and lose their value between
calls.

SCODE

A long integer value that is used to pass detailed information to the caller of an
interface member or API function. The status codes for OLE interfaces and
APIs are defined in FACILITY_ITF.

Script level

Any code outside a procedure is referred to as script-level code.

Seed

An initial value used to generate pseudorandom numbers. For example, the


Randomize statement creates a seed number used by the Rnd function to create
unique pseudorandom number sequences.

String comparison

A comparison of two sequences of characters. Unless specified in the function


making the comparison, all string comparisons are binary. In English, binary
comparisons are case-sensitive; text comparisons are not.
For more QTP Realtime Sripts, visit
www.ramupalanki.com

String expression

Any expression that evaluates to a sequence of contiguous characters. Elements


of a string expression can include a function that returns a string, a string literal,
a string constant, or a string variable.

Type library

A file or component within another file that contains standard descriptions


of exposed objects, properties, and methods.

Variable

A named storage location that can contain data that can be modified during
program execution. Each variable has a name that uniquely identifies it within its
level of scope.
Variable names:

• Must begin with an alphabetic character.

• Can't contain an embedded period or type-declaration character.


VB Script For QTP 83

• Must be unique within the same scope.

• Must be no longer than 255 characters.

Anda mungkin juga menyukai