For Each - Next (Arrays)

You can iterate through the elements of an array using a For Each - Next loop
The data type of vItem must be Variant.
When you use this type of loop all the items are Read Only.
This type of loop cannot be used to update any values in the array.


Fixed Array - Read Only

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

Multi Dimensional Array

This declares a 2-dimensional array and iterates through the elements one dimension at a time.

Public Sub ForEachLoop3() 
Dim arValues As Variant
Dim vItem 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 vItem In arValues
      Debug.Print vItem
   Next vItem
End Sub

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