Using Loops to Repeat Code (VBA Programming Concepts) (AutoCAD VBA)

This section shows you how to execute a block of code repeatedly, for a specified number of times using the For loop, or until a certain condition arises using the While loop. You’ll find these two loops used in many of the coding exercises throughout this topic. The For loop is especially useful when all the objects in a collection need to be accessed, and the While loop is especially useful for data input from either a file or the user.

Repeating Code a Set Number of Times

When you want to repeatedly execute a block of statements a specific number of times, use a For loop. The For loop has the following structure:

tmp757e-157_thumb

where Counter is the variable that keeps tabs on how many times the loop has been executed.

When the For loop is first entered, the Counter variable is initialized to Start. All the statements are then executed until the Next clause. If a step has been specified, it is added to the Counter; otherwise, Counter is incremented by one, which is the default. Steps specify how much the counter is incremented and can be positive or negative; negative steps are used when the value assigned to Start is greater than the value assigned to Finish.


When the Counter variable becomes greater than the Finish value (or less than,if you’re using negative steps), code execution jumps to the statement after the Next clause.

The variable used for the loop counter should never be updated inside the loop. This may lead to a never-ending loop or the loop may be terminated prematurely.

The For loop is ideal for processing the data values in an array With an array, the Start and Finish values are replaced by the index value for the first and last elements in the array. For example, to change the color of all the lines stored in the AllLines array to green, use the following code:

tmp757e-158_thumb

For loops can be nested inside other For loops, which is ideal for processing multidimensional arrays. For example, consider the following three-dimensional array:

tmp757e-159_thumb

To initialize all the elements in this array to zero, you’d use the following code:

tmp757e-160_thumb

Although it’s not a requirement, placing the loop counters after the Next clauses can improve the readability of your code, especially when several For loops are nested inside one another. The loop counters become even more important when there are lots of statements.

There is also a For Each loop that allows you to access each item from a collection of objects or an array. The syntax of the For Each loop is given in The Microsoft Forms Object Model section later in this topic.

Next post:

Previous post: