QTP VBScript Looping Through Code


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.


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

9.1.1 Repeating Statements While a Condition is True


Repeats a block of statements while a condition is True or until a condition becomes True

a) 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 b) Do Statements ----------- ----------- Loop While condition Example: Dim x x=1 Do Msgbox "Hello G.C.Reddy" Msgbox "Hello QTP" x=x+1 Loop While x<5
9.1.2 Repeating a Statement Until a Condition Becomes True

c) Do Until condition
Statements
-----------
-----------
Loop
Or, we can use this below syntax:
Example:

Dim x
Do Until x=5 x=x+1
Msgbox "G.C.Reddy"
Msgbox "Hello QTP"
Loop
Or, we can use this below syntax:
d) 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"
x=x+1
Loop Until x=5

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

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

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

Post a Comment

أحدث أقدم