Enhanced For-Next loops

Enhanced For-Next loops

At times you may need to execute the same block of statements for different values of a variable, but you can’t use a straight For Next loop because the sequence of values is not regular. For example, you may need to repeatedly call a given procedure passing the first ten prime numbers as arguments:

DoSomething 2DoSomething 3DoSomething 5DoSomething 7DoSomething 11DoSomething 13DoSomething 17DoSomething 19DoSomething 23DoSomething 29

Here is a better approach, based on the Array() function that builds a Variant array on the fly, and a For Next loop that iterates on it:

Dim v As VariantFor Each v In Array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)    DoSomething vNext

You can exploit this trick to build loops that aren’t even based on numeric control variables:

Dim v As VariantFor Each v In Array("Spring", "Summer", "Fall", "Winter")    PrintSaleReport vNext


Share the Post: