Adding Control Statements

Because the body of the loop typically contains at least one statement that affects the results of the loop, you can use incremental statements, such as counter variables, within the body of a loop to change the condition of the loop. A counter variable has a specific constant added to it each time the loop executes. Typically, you declare a counter variable as an integer data type and initialize it with a start value outside the loop. Within the loop, you increment the variable by a constant value.

In the following example, the macro assigns the counter variable J an initial value of 1. The Do While loop verifies that it is less than 5, and then executes the loop. The loop assigns a value of 1 to the first cell on the worksheet, cell A1. The counter variable J increments to 2 and the loop retests the condition. The looping continues until the condition is false. In this instance, the loop repeats only four times. When J has a value of 5, the looping stops.


ActiveSheet.Rows(J).Cells(1).Value = J J = J + 1 Loop

Looping While Vba

• Switch to Excel and run the macro.

■ The body of the macro repeats until the maximum counter value is met.

-H Type N = N + 1 to increment the counter variable.

Type Loop to mark the end of the Do While loop.

■ If you skipped step 5, type While N < M to specify the condition of the loop, replacing M with the maximum value for the counter variable and N with the variable specified in step 2.

• Switch to Excel and run the macro.

Was this article helpful?

0 0

Post a comment