A For Each loop is when we want to execute a statement or a group of statements for each element in an array or any collection.
A For Each loop is similar to the For Loop; however, the loop is executed for the each element in an array or a group. Hence, the step counter don't exist in for each loop. It is mostly used with arrays or used for 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 Elements
[statement 1] ' code that need to be executed on each element
[Exit For] ' when you want to exit from the loop
Next
Example
|
Code
|
|
Sub demo_foreachloop()
Dim fruitnames As Variant 'let
fruits is an array
fruits =
Array("apple", "orange", "mango")
'iterating using For each loop.
For Each Item In fruits
fruitnames = fruitnames
& Item & “ ”
Next
MsgBox fruitnames
End Sub
|
|
OutPut
|
|
apple
orange
Mango
|
0 Comments