In the previous article, you learned about the
For loop, however, there is another loop called
For...Each loop similar to
For...Each loop is suitable to go through each item of a collection or an array.
Syntax: For…Each Loop
The syntax for the For..Each loop is given below.
For Each element In group [Statements] [Exit For] [Statements] Next [element]
The keywords are very much similar to for loop but with a difference that the
For...Each loop is suitable for array.
Example Program: For…Each Loop
Private Sub Command1_Click() Dim NumArray(2) As String NumArray(0) = "Ram" NumArray(1) = "Jaya" NumArray(2) = "Bruce" For Each ArrayItem In Num Array MsgBox (ArrayItem) Next ArrayItem End Sub
The above program goes through each item of the array and display the result.
Output – For…Each Loop
In the program above, each time you click on the “OK” button, a different name from the array is displayed.