For - Next

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


1 Dimensional


Public Sub ForNextLoop1() 
Dim arValues As Variant
Dim oItem As Variant
Dim iArrayCount As Integer
   arValues = Array(1, 2, 3, 4, 5)
   
   For iArrayCount = 0 To UBound(arValues)
      oItem = arValues(iArrayCount)
      Debug.Print oItem
   Next iArrayCount
End Sub

2 Dimensional


Public Sub ForNextLoop2() 
Dim arValues As Variant
Dim oItem As Variant
Dim iArrayCount1 As Integer
Dim iArrayCount2 As Integer
   arValues = Array(Array(1, 2), Array(3, 4), Array(5, 6), Array(7, 8))
   
   For iArrayCount1 = 0 To UBound(arValues, 1)
      For iArrayCount2 = 0 To UBound(arValues(0), 1)
         oItem = arValues(iArrayCount1)(iArrayCount2)
         Debug.Print oItem
      Next iArrayCount2
   Next iArrayCount1
End Sub


Public Sub ForNextLoop3() 
Dim arValues As Variant
Dim oItem As Variant
Dim iArrayCount1 As Integer
Dim iArrayCount2 As Integer
   
   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 iArrayCount1 = 0 To UBound(arValues, 1)
      For iArrayCount2 = 0 To UBound(arValues, 2)
         oItem = arValues(iArrayCount1, iArrayCount2)
         Debug.Print oItem
      Next iArrayCount2
   Next iArrayCount1
End Sub




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