Repeating Code an Unknown Number of Times (VBA Programming Concepts) (AutoCAD VBA)

When you want to repeat a block of code while some condition evaluates to True (or False), but you don’t know the number of times required, you need to include a While loop. The structure of the While loop is as follows:

tmp757e-161_thumb

One of the most common uses of the While loop is to read data from a file when it is not always clear how many data items are actually in the file.

When the interpreter enters the While loop, it evaluates the condition. If the condition evaluates to True,the statements inside the While loop are executed until the Wend clause is encountered. Then the interpreter jumps back up to the start of the loop and evaluates the condition again. This looping is repeated until the condition becomes False, when execution jumps down to the statement after the Wend clause.

While loops are the most likely cause of a program’s failing to stop, so great care must be exercised to ensure that at least one of the variables in the condition actually changes inside the loop. The best place to update this variable is in the statement preceding the Wend clause.


There is also a Do loop that lets you choose whether the condition is checked at the beginning or the end of the loop.

Next post:

Previous post: