Looping

For simple 1-dimensional arrays, the For-Each-Next tends to be faster than the For-Next.


For - Next

You can iterate through the elements of an array using a For - Next loop.

Public Sub ForNextLoop() 
Dim arValues As Variant
Dim vItem As Variant
Dim iArrayCount As Integer
   arValues = Array(1, 2, 3, 4, 5)

   For iArrayCount = 0 to UBound(arValues)
      vItem = arValues(iArrayCount)
      Debug.Print vItem
   Next iArrayCount
End Sub

For Each - Next

You can iterate through the elements of an array using a For Each - Next loop.
The data type of vItem must be Variant.

Public Sub ForEachLoop() 
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

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