Difference between For Loop and For Each :
- For loop is to do something over and over again until the task has been completed.
- ForEach works only on arrays. even it will run the loop until end of the array.
Please find below in details with Example :
For Loop in Vbscript :
A for loop is a repetition control structure that allows a developer to efficiently write a loop that needs to execute a specific number of times.
Syntax :
For counter = start To end [Step stepcount]
'Actions to be performed
Next
Example :
Dim a : a=5
For i=0 to a Step 1 'i is the counter variable and it is incremented by 2
Msgbox "The value is i is : " & i
Next
Output :
The value is i is : 0
The value is i is : 1
The value is i is : 2
The value is i is : 3
The value is i is : 4
The value is i is : 5
For..Each Loop in Vbscript :
A For Each loop is used when we want to execute a statement or a group of statements for each element in an array or collection.
A For Each loop is similar to For Loop; however, the loop is executed for each element in an array or group. Hence, the step counter won't exist in this type of loop and it is mostly used with arrays or used in context of File system objects in order to operate recursively.
Syntax :
For Each element In Group
' Actions to be performed
Next
Example :
'fruits is an array
fruits=Array("apple","orange","cherries")
Dim fruitnames
'iterating using For each loop.
For each item in fruits
fruitnames=fruitnames&item&vbnewline
Next
msgbox fruitnames
Output :
apple
orange
cherries