VBA - For Each Loops


Advertisements

A For Each loop is used 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. It is mostly used with arrays or used in context of the File system objects in order to operate recursively.

Syntax

Following is the syntax of a For Each loop in VBA.

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

Example

Private Sub Constant_demo_Click()  
   'fruits is an array
   fruits = Array("apple", "orange", "cherries")
   Dim fruitnames As Variant
 
   'iterating using For each loop.
   For Each Item In fruits
      fruitnames = fruitnames & Item & Chr(10)
   Next
   
   MsgBox fruitnames
End Sub

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

apple
orange
cherries
vba_loops.htm
Advertisements