For loop to traverse only  filled list indexes or entries from collections

The loop requires a running variable. The example below uses the run variable i. The running variable is set with the first filled value of the variable list k. When the End For is reached, the value of the next filled index in the list is passed to the running variable. As a result, unfilled indexes are skipped. If all elements of the k variable list have been processed, the code continues to End For.

The loop can be aborted prematurely with the Exit For command.

The loop can be continued with the Continue command at the next filled index value.

 

Dim i As Long, k() As Long

 

k := List(10, 20, 30)

k(100) := 1000

 

For Each i In k

   If (i + 100) >= 120 Then

      Exit For

   EndIf

End For