For Each - Next

This gives you access to all the elements in an Array or Collection without knowing (or checking) exactly how many elements there are.
The data type of oItem must be Variant.


Elements in an Array

This loops through all the items in the array.

Public Sub ForEachNext1() 
Dim arValues As Variant
Dim oItem As Variant
   arValues = Array(1,2,3,4,5)
   For Each oItem In arValues
'do something
   Next oItem
End Sub

Elements in a Collection

This loops through all the items in the collection.

Public Sub ForEachNext2() 
Dim MyCollection As New Collection
Dim oItem As Variant
   MyCollection.Add "on"
   MyCollection.Add "tw"
   MyCollection.Add "th"
   MyCollection.Add "fo"
   For Each oItem In MyCollection
'do something
   Next oItem
End Sub

Exit For

The Exit For statement lets you exit the loop early.


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext