devxlogo

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

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.