VBA - For Each Loops
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 excel vba foreach 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.
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] excel vba foreach [statement 22] Next
ExamplePrivate Sub Constant_demo_Click() excel vba foreach '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 Excel vba foreach fruitnames End Sub
When the above code is executed, it prints all the fruit names with one item in each line.apple orange cherries