For - Each

You can iterate through the elements of an array using a For - Each loop
The element must be declared with a Variant data type


1 Dimensional


Sub ForEachLoop1() 
Dim arValues As Variant
Dim oItem As Variant
   arValues = Array(1, 2, 3, 4, 5)
   
   For Each oItem In arValues
      Debug.Print oItem
   Next oItem
End Sub

2 Dimensional

This approach allows you to access both the dimensions

Public Sub ForEachLoop2() 
Dim arValues As Variant
Dim oItem As Variant
   arValues = Array(Array(1, 2), Array(3, 4), Array(5, 6), Array(7, 8))
   
   For Each oItem In arValues
      Debug.Print oItem(0)
      Debug.Print oItem(1)
   Next oItem
End Sub

This type of 2-dimensional array iterates through the elements one dimension at a time.

Public Sub ForEachLoop3() 
Dim arValues As Variant
Dim oItem As Variant
   ReDim arValues(0 To 3, 0 To 1)
   arValues(0, 0) = 1
   arValues(0, 1) = 2
   arValues(1, 0) = 3
   arValues(1, 1) = 4
   arValues(2, 0) = 5
   arValues(2, 1) = 6
   arValues(3, 0) = 7
   arValues(3, 1) = 8
   
   For Each oItem In arValues
      Debug.Print oItem
   Next oItem
End Sub


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