There will be some situations where we do not know the number of iterations, but we need to execute a block of code for all the elements in an array (its a data type) or for all the objects. Here, array and object concepts are new but having look at the following script makes it more clear.
Dim fruits() ReDim fruits(100) nofruits=0 For i=0 to 100 fruits(i)=inputbox("Enter the name of a fruit") ans = MsgBox("Do you want to continue", vbYesNo, "Confirm Continuation...") If ans=vbNo Then Exit For End If nofruits=nofruits+1 Next ReDim Preserve fruits(nofruits) fruitnames="" For each fruit in fruits fruitnames=fruitnames&fruit&vbnewline Next msgbox fruitnames
In the above script, initially we do not know how many fruit names we are going to enter and so, we have declared the array size as 100 (a max number, this can even be 1000). Then we inserted some names into the fruits array. In the next step using For Each Next we have successfully displayed all the names of the fruits which was entered and kept in fruits array.
The difference between For Next and For Each Next we can observe from the above example is that in the former we need to specify the initial and maximum value where as in the latter we need to provide just the array. The same concept can even be applied to a collection of objects.
Let us try to decompose the above script and understand how it works.
- fruits is a dynamic array so it is declared as fruits() (just the brackets and no numbers)
- ReDim – ReDimension. This keyword resets the number of elements that can be accommodated in the array.
- In the first For loop we are accepting the fruit names from the user and inserting them into the fruits array.
- The msgbox with vbYesNo argument displays a confirmation popup with Yes & No buttons. If the user clicks on Yes / No then the next if statement evaluates the condition. If the user clicks on No then the Exit For gets executed and control comes out of the For Loop.
- ReDim Preserve – keywords will preserve the earlier elements in the array and also changes the array size.
- For Each Next extracts the fruit names stored in the array and msgbox displays the output on the console.
The above example clearly explains the way the For Each Next works and also compares with the For Next variant of for loop.