site
stats
By Anish Pillai Anish Pillai Posted under qtp and vbscript tutorials | QTP Tutorials for Beginners

Part 5: QTP and VBScript | Looping through Code

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- 0 Flares ×

In this fifth installment of QTP VBScript Tutorial series, we would cover the various looping statements that are available in VBScript. Looping statements allow you to repeatedly execute a set of statements multiple times. The number of times the code is executed depends upon many factors such as some loops are executed until a condition is True or False while some other loops are executed a fixed number of times. VBScript provides you with the following four looping statements –

  • .. For Loop
  • .. Do While Loop
  • .. Do Until Loop
  • .. For Each Loop

Let’s see each of these four loops one by one.

For Loop

For Loop uses a counter to run a group of statements a specified number of times. Lets see an example of for loop where the codes finds out the sum of numbers from 1 to 10.

Dim iSum
iSum = 0

'Loop through the numbers
For i=1 to 10
  iSum = iSum + i
Next

'Display the result
msgbox "Result is: " & iSum


In the above example you would have noticed that the counter, i, is incremented by a value 1. If you wish you can change the default value to any other value. This can be done using the Step property. Let’s see an example where the code finds out the sum of first 10 odd numbers.

Dim iSum
iSum = 0

'Loop through the numbers
For i=1 to 20 Step 2
  iSum = iSum + i
Next

'Display the result
msgbox "Result is: " & iSum


Do While Loop

Do While Loop runs a set of statements while a condition is True. This means that the loop will continue execution till the condition is true and would stop only when the condition becomes false. In a Do While loop the condition can be evaluated at two places. These are –
a) before you enter the loop.
b) at the end of the loop after it has run once. In this case, the loop is executed at least once even if the condition is false because the condition is checked at the end of the loop after it is run once.

Let’s see examples of both these types of Do While Loop.
a) Evaluation of condition before entering the loop.

'Code to find the sum of first 10 numbers

Dim iSum, iCounter
iSum = 0 : iCounter = 1

'Check the condition at the beginning of the loop
Do While iCounter <= 10
  iSum = iSum + iCounter

  'Increment the counter
  iCounter  = iCounter + 1
Loop

'Display the result
msgbox "Result is: " & iSum


b) Evaluation of condition at the end of the loop after it is run once.

'Code to find the sum of first 10 numbers

Dim iSum, iCounter
iSum = 0 : iCounter = 1

'Check the condition at the end of the loop
Do
  iSum = iSum + iCounter

  'Increment the counter
  iCounter  = iCounter + 1
Loop While iCounter <= 10
'Display the result
msgbox "Result is: " & iSum


Do Until Loop

Do Until loop is similar to Do While loop with the only difference being that the loop is run until the condition becomes True. In other words, the loop will be executed till the condition is false and would exit only when the condition becomes true. In Do Until Loop also you can check the condition before the beginning or at the end of the loop. Lets take the examples used for Do While loop and see how it can be used for Do Until loop.

a) Evaluation of condition before entering the loop.

'Code to find the sum of first 10 numbers

Dim iSum, iCounter
iSum = 0 : iCounter = 1

'Check the condition at the beginning of the loop
Do Until iCounter > 10
  iSum = iSum + iCounter

  'Increment the counter
  iCounter  = iCounter + 1
Loop

'Display the result
msgbox "Result is: " & iSum


b) Evaluation of condition at the end of the loop after it is run once.

'Code to find the sum of first 10 numbers

Dim iSum, iCounter
iSum = 0 : iCounter = 1

'Check the condition at the end of the loop
Do
  iSum = iSum + iCounter

  'Increment the counter
  iCounter  = iCounter + 1
Loop Until iCounter > 10

'Display the result
msgbox "Result is: " & iSum

In the above examples you would have noticed that the when we used the Until statement, we changed the condition to ‘iCounter > 10’. So here the loop will run till the value of iCounter is less than or equal to 10. The loop would exit only when the value becomes greater than 10.

For Each Loop

For Each loop is different from other loops discussed above for the reason that For Each loop repeats a set of statements for each item in a collection/object or for each element in an array. Let’s see some examples of For Each Loop.

Example 1: To find all elements in an array using For Each Loop

'Declare and initialize an array
Dim arr(2)
arr(0) = "automation"
arr(1) = "repository"
arr(2) = "qtp"

'Loop through the elements of the array
For Each oArr in arr

 'Display the array element
  msgbox oArr

Next

'How the same information can be extracted using For Loop
iTotalItems = UBound(arr)

For i=0 to iTotalItems

  'Display the array element
  msgbox arr(i)

Next


Example 2: Find all the files in a given folder using For Each Loop

'Get instance of all the files in a given folder
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("D:\")
Set oFiles = oFolder.Files

'Loop through all the files in 'D:\' Drive
For Each file in oFiles

  'Display the name of the file
  msgbox file.Name

Next


This was all about the basics of the different looping statements that you can use in VBScript. In the next article, we would cover come more aspects of VBScript looping statements.

If you enjoyed this article, you can join our blog to get new articles delivered directly in your inbox.

To check out more tutorials, visit our QTP Tutorials page. You can also check the Archives page to view the list of all our articles.

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- 0 Flares ×
  • Pingback: Part 6: QTP and VBScript | Nested Loops in QTP - Automation Repository - Automation Repository()

  • Pat

    Hi, I learn a lot from your posts. Thanks:)
    You have indefinite loop in "Do While Loop". You forgot to put iCounter < 10.

    • Anish10110

      Hi Pat.. Thanks for pointing out the error. I have corrected the code.

  • Keerti

    Hi Anish,

    I found your posts very much useful.Uyou have very well taken care of making the starters understand the concept.Thanks .But as mentioned by Pat,uyou need to make that small correction in the code.

    • Anish10110

      Thank you Keerti.. 🙂 Its very encouraging to hear good feedback like this.. Regarding the code, I had changed it last time also. But I think this has got something to do with the formatting. I have corrected the error.. Thanks. And keep visiting. 🙂

  • vidya

    i learnt a lot from ur site….it is very easy to understand and learn….

    • Anish10110

      Thank You Vidya… 🙂

  • VijayS

    I just started learning this vb script today. The topics are crisp and clear. I have a question on the following.
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder("D:")
    Set oFiles = oFolder.Files
    It would be nice, if you could explain the above this little more. Also please provide what are all the basic commands we have to perform on files. (read, write, delete, etc)

    • Anish10110

      Hi Vijay,

      The above lines are very easy…

      Set oFSO = CreateObject("Scripting.FileSystemObject") — This creates an object of type FileSystemObject which enables the object to access all the methods of FileSystemObject.
      Set oFolder = oFSO.GetFolder("D:") — Here a new object is created whose reference is set to D: Drive in our computer.
      Set oFiles = oFolder.Files — Here, by using the folder object created above, we can access all the files that are present in that drive (D: in this case)

      Also, do you have QTP installed in your system. If yes, then you can refer to QTP help where you will find complete reference to all the File System Operations. You can also check MSDN reference for all the FileSystemOperations. Check this link for more details – <a href="http://msdn.microsoft.com/en-us/library/aa711216%28v=vs.71%29.aspx&quot; target="_blank">http://msdn.microsoft.com/en-us/library/aa711216%…</a>

  • Seshu

    Thanks for the tutorial. This is pretty good and useful for beginers like me.

  • Poomariappan

    Hi I need to read the all files from directory and i am doing some operation in the file names I am using For Each statement its supporting first time time only how to write block value

    Example

    On Error Resume Next

    Dim fso, folder, files, NewsFile,sFolder

    Set fso = CreateObject("Scripting.FileSystemObject")

    sFolder = "C:Userspshanm12mariaudit_manager_reportsReports"

    If sFolder = "" Then

    Wscript.Echo "No Folder parameter was passed"

    Wscript.Quit

    End If

    Set NewFile = fso.CreateTextFile("FileList.txt", True)

    Set folder = fso.GetFolder(sFolder)

    Set files = folder.Files

    For each folderIdx In files

    NewFile.WriteLine(folderIdx.Name)

    Wscript.Echo folderIdx.Name

    Next

    NewFile.Close

    This code fetch the output only one file how to get the all files in the VB script.

    Please help me some one.

    Thanks

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Email -- 0 Flares ×