VBA FOR EACH loop in Excel
The "For Each" loop is used to iterate through a collection in Arrays.
There is not any condition clause as in "For Loop"
This statement is most useful when iterating through unknown number of items in a Collection.
- For Each
The following example illustrates the use of "For Each "
- Sub for_each()
- Dim str() As String
- str = Split("Welcome @ to @ VBA!!", "@")
- For Each s In str
- MsgBox s
- Next s
- End Sub
The above example splits a string(str) into an Array and is displayed in a Message box with "For Each" loop
Note that, The number of stings in the Array will be unknown, when it has to be got from the user during runtime.
The Result of the above code is as below