Flow Control (Loop Statements)
- Looping allows us to run a group of statements repeatedly.
- Some loops repeat statements until a condition is False;
- Others repeat statements until a condition is True.
- There are also loops that repeat statements a specific number of times.
- The following looping statements are available in VBScript:
- Do...Loop: Loops while or until a condition is True.
- While...Wend: Loops while a condition is True.
- For...Next: Uses a counter to run statements a specified number of times.
- 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
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<br"> Msgbox "Hello G.C.Reddy"
Msgbox "Hello QTP"
Loop
ii) 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 br="">
5>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
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"
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<br"> msgbox "Hello G.C.Reddy"
msgbox "Hello QTP"
Wend
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
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 5>
No comments:
Post a Comment