VBScript For...Each Loops

Advertisements


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:

The syntax of a For Each loop in VBScript is:

For Each element In Group
  [statement 1]
  [statement 2]
  ....
  [statement n]
  [Exit For]
  [statement 11]
  [statement 22]
Next

Example:

<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
  
 '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
   
</script>
</body>
</html>

When the above code is executed, it prints all the fruitnames with one item in each line.

apple
orange
cherries


Advertisements
Advertisements