Control Flow in VBScript or UFT
This post talks about control flow statements in VBScript, control flow statements in UFT, control flow in VBScript, control flow in UFT. 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.
Flow control in VB script
The order of execution is known as flow in VBscript. The flow gets executed top to bottom, in a sequential way and keep executing it until the end reaches.
Branching and flow control is very common when we are dealing with inputs to our scripts from dataset or from users.
Control of flow in VBScript or UFT
The logic that allows us to manipulate the execution of the code in our script is called control flow.
Control flow is divided into below section
1. Branching/comparison statements
This branching statement provides scripts with intelligence. Expressions/ conditions are the ones to be tested to get a True/ False outcome.VB script supports if else, endif, select branching is a technique by which depending on some condition few statements gets executed and some are not.
1.1 if end if
1.2 if else endif
1.3 select case
Looping is a technique which allows us to execute the same lines of code or block of code over and over until loop condition terminates it.
2.1– For next[ for a predefined number of times]
2.2– Do while loop[ for a specific condition is true]
2.3– Do loop until[for a specific condition to be true]
2.4– For each next[For Each…Next Iterates through properties of an object ]
2.5—Do loop while [for a specific condition to be true]
2.6– Do until loop[for a specific condition to be true]
2.7– While -Wend
Conditional construct in VBScript or Conditional construct in UFT
Comparison statements allow us to perform conditional logic tests between two expressions or values.
Note – It is always better to write start and end block of branching and looping before actual code block implementation.
Space or White space is used for human consumption of the code. If we do not provide space machine can still understand the code. In that case, human readability will go down.
General indentation rule is to provide white spaces if the next line is a subcode of the above code.
If( condition) then ---- do something ---- do something ---- do something end if
it will visually suggest the coding structure. The logical structure of the code should be in such way that without even reading it, we can look at the code and consciously and unconsciously we can get a sense on how the code is organized and how it works.
Select case— it is upgraded version of multiple if–else statements. It provides an output based on a list of possible matching expressions.
Dim userNumber Dim reply userName= Inputbox("Enter your number") reply= "the number is "& userNumber." msgbox reply
if the user does not put any value still the message box is going to display” the number is” string and userNumber is blank hence it won’t print anything.
A better approach
dim userNumber dim reply userNumber= Inputbox(" enter your number") If(userNumber="") Then reply="Please put some number" msgbox reply else reply="your number is"&userNumber msgbox reply End if
Details of If in VBScript or UFT
If — it compares two expressions or values and either perform some set of statements or skip some statements. Also If tests the expression then keyword execute the true condition execute true condition else executes the false part.
If Else EndIf constructs a block of code.A block of a code is such segretion of code which is having a start and end.
if [expression] Then Statements End if
If works on boolean value hence all the expression used in if condition must boolean output. The code resides inside if- else endif is called a block of code. Where If is the starting point of the block and Endif is the end point of if block. Block of code is often referred to as a group of statements.
Variations of if
Case 1 of If the variation
Instead of a Boolean expression, we can use mathematical expression too.
If(3-2)=1 then Statements End if
Case 2 If the variation
If a function returns a Boolean value that can be used as if.
If isString(myvar) then Statements End if
Case 3 If the variation
We can multiple tests inside of if. They are valid as long as they are yielding Boolean value.
If( isNumeric(myvar1) and (isNumeric(myvar2) Then Statements End if
Case 4 If the variation
We can use NOT statement to invert the expression.
If(NOT (isNumeric(myvar)) Then Statements End if
We can upgrade if block by attaching an else block. Else block get executed when if block is evaluated as false.
If isDigit(myvar) then Statements Else Statements End if
Else If block
The Else if block is a modified multi way switch. Else If has two variants.
- Else If with optional else
- Plain Else if without else.
Else if with optional else
In this case if the first comparison fails,control goes to first ElseIf and execution continues in the same manner.
If isDigit(myvar) Then Statements ElseIf isDate(myvar) Then Statements Else Statements End If
Else If without else
If isDigit(myvar) Then Statements ElseIf isDate(myvar) Then Statements End If
Nesting of If Else
IfElseEndIf can be extended through the use of ElseIf clause and through nesting. Nesting is the technique of placing a block of code inside of another block of code of the same type. we can nest if else inside another if else block. There is no rule to create nested if else as Long as the logic is correct and the code is manageable. Going too deep may raise logic issues. It may create less readability and hard maintainability.
If( accountNo.IsValid( )) If IsEmployee(accountNo) then If IsVendor(accountNo) then msgbox "bonus is 5%" else msgbox "not a vendor anymore" End If If IsRegular(accountNo ) then msgbox "bonus is 7%" Else msgbox "not a valid regular employee" End if Else msgbox "account no does not belong to a valid employee" Else msgbox "not a valid account no" End if
If isNumeric( myvar) then If( myvar less than 25) then Statements Else if((myvar less than 40) and(myvar greater than 26)) then Statements End if Else statements End if
The indenting is very important to identify which lines of code are subordinate to the lines above them.
Select case- switch
Instead of using multiple if else statement, we can use switch statements to implement multiple paths. It can test multiple conditions at a single go. Select end select block is an upgraded version of series of if end if statements.
Select is useful when we are expecting same type of outcomes from a test. Where as the If..Else..EndIf block can test other outcomes too.
Note:- end of select- if end if is more flexible and user-friendly as we can test lots of extra conditions or expressions where as select only takes into account of the various outcome of a single expression.
Select case[expression] Case [case statement1] Statements Case [case statement 2] Statements Case [case statement 3] Statements Case else Statements End select
Else case is a default case if no case statement is matching with the given case statement. The default or else case gets executed.
Select case mycolor Case VbBlack msgbox "black" Case VbWhite msgbox "white" Case VbBlue msgbox "blue" Case else msgbox " The color code is not valid" End select
Switch case is more efficient than if else. If end if statement as at one goes it can execute the possible cases.
Note:- The else case is the default condition hence it should never be executed in a regular scenario.
Nesting of the select case:
We can put nesting of the select case to nth level as long as we are not complicating the logic, losing readability. The best practice says up to the second level is good.
select Case varType(myVar) Case vbString select case myVar case "username" If trim(myusername)="" then statement Else statement End If Case "password" If trim(password)=""then statement else statement End if End select Case vbInt statement Case Vblong statement Case Else End Select
Do we need Case Else in Select?
Yes, it is a best practice even if the situation does not appear.
- If any of the expected outcome from a step changes drastically,else block of the select case gets triggered and we can determine the issue in a very quick manner.
- Gives a clear idea in terms of documentation as to what data we do not expect in Else block.
Loop Construct in VBScript or Loop construct in UFT:
The loop is useful when
- We want to repeat a block of code until termination condition(typically a Boolean condition yields true or false.)
- We want to repeat a block of code for a predefined finite number of times.
Advantages of Looping:
- 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.
For Each…… Next loop
These loops solve the problem when traversing a collection( a data structure to hold objects of the same type).
Exp-file system object represents a folder which is a collection of files. It also provides the ability to iterate over properties belongs to an object. Along with this it also helps to work on an object.
Element is a variable that represents an object property or an element stored in the array. The collection is the name of the data structure.
Syntax of For Each… Next Loop
For Each Element In Collection statements Next [Element]
Example of For Each…Loop
'Header Information Option Explicit Dim myobjFSO,myFolder,myobjFile 'Reference section 'Task section Set myobjFSO=WScript.CreateObject("Scripting.FileSystemObject") Set myFolder=myobjFSO.GetFolder("D:\\test\") 'worker section For Each objFile in myFolder.Files 'Output section msgbox objFile.name Next 'tear down section set myobjFSO=nothing
For Each…Next on Array
'Header Information section Option Explicit Dim myArray(5) Dim arrayElement 'Reference information section myArray(0)="banana" myArray(1)="grape" myArray(2)="apple" myArray(3)="pineapple" myArray(4)="papaya" 'task section For each myArrayElement in myArray 'output section msgbox myArrayElement Next 'tear down section.
Note For…..next and for each…next both loops use Exit For to jump out of the loop. A popular way to break the loop.
While……. Wend loop
This is not a trendy looping style or an older style but still valid while loop.
Option Explicit Dim myVar=0 While myVar<=10 msgbox myVar myVar=myVar+1 Wend
There is no breaking syntax for a while.
For… Next loop
The for…next loop is useful when-
- we want to execute a code block for a known finite number of times.
- we want to execute a code block for each element in a structure(not on collection)
The syntax for For loop
For is the basic loop that iterates for a specific number
For index= begin to end,[ optional step] Statements Next [Index]
The index is the loop control variable that the for loop tracks and iterates the statements given as part of for loop.
End is the number till the for loop iterates.
[Optional] step value is the number signifies how the index will be incremented or decremented. If no Optional step value is defined, VBScript treats that as step 1. That is the loop control variable will be increased by one till end occurs.
Dim myIndex= 1 For myIndex= 1 to 5 msgbox "hello" Next
How to stop an infinite loop?
Being a coder we might make a mistake to give a wrong condition, as a result, our loop may go to an infinite loop. We always need to put safety net against any loop so that after a certain period, it checks the loop validity. If the loop is invalid we need to break it by using the code.
How to break a For Loop
We can break a For loop by using a keyword called Exit For.
Do loop is an elegant looping style where we can control the looping as per our need. Also, do loop block executes at least once before checking the condition. Do loop execute a collection of statements until a specific condition is true. And do the loop comes with two variations.
Even for do loop , indentation plays a major role. The indentation should make the code easy to identify.
- do while loop( till a condition is valid)
- do until loop( till the condition becomes valid)
The ‘Do’ is the starting of the do loop. It tells the script engine that a block of code that will define a do loop has been started. The script engine then will look for the the body of the do loop and will also see the Loop statement somewhere down in the code.
Example of Do while loop
Dim myVar myVar=1 Do while myVar<3 msgbox myVar myVar=myVar+1 loop
Dim myVar myVar=1 Do msgbox myVar myVar=myVar+1 loop while myVar<3
An important statement that controls the do loop controller variable. If we by mistake do not provide this control statement the loop will become an infinite loop.
Do Until Loop
Dim myVar myVar=1 Do until myVar=10 msgbox myVar myVar=myVar+1 Loop
Dim myVar myVar=1 Do msgbox myVar myVar=myVar+1 Loop Until myVar=10
Do while/ until loops have the ability to accept data from user and control the execution.
Position of while and until in a do loop
While and until can be positioned along with doing or along with loop statement. Now when to use do while/ until?
In case you want to test the precondition first then execute the do loop, we need to position the condition along with doing. It is pre checking of the condition.
In case our loop to execute at least once then check the postcondition. we need to position then along with loop statement. This is post checking of the condition.
When to choose until and when to choose while is a do loop?
It depends on the individual coding style and preference. As per MSDN “repeats a block of statements while a condition is true or until a condition becomes true”.
In a general test, a false value for the condition in until and test a true value in while.
How to break do loop?
The keyword that helps us to break a do loop is Exit Do.
Dim myVar myVar=1 Do until myVar=10 If myVar=5 then Exit Do End If msgbox myVar myVar=myVar+1 Loop
One should not forget to end the loop. Otherwise the loop may go on and on and becomes an infinite loop. Infinite loops are undesirable.