30.04.2017 Views

4523756273

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10: Controlling Program Flow and Making Decisions<br />

153<br />

Next statement are the statements that get repeated in the loop. To see how<br />

this works, keep reading.<br />

A For-Next example<br />

The following example shows a For-Next loop that doesn’t use the optional<br />

Step value or the optional Exit For statement. This routine loops 20 times and<br />

uses the VBA Rnd function to enter a random number into 20 cells, beginning<br />

with the active cell:<br />

Sub FillRange()<br />

Dim Count As Long<br />

For Count = 0 To 19<br />

ActiveCell.Offset(Count, 0) = Rnd<br />

Next Count<br />

End Sub<br />

In this example, Count (the loop counter variable) starts with a value of 0<br />

and increases by 1 each time through the loop. Because I didn’t specify a<br />

Step value, VBA uses the default value (1). The Offset method uses the value<br />

of Count as an argument. The first time through the loop, Count is 0 and<br />

the procedure enters a number into the active cell offset by zero rows. The<br />

second time through (Count = 1), the procedure enters a number into the<br />

active cell offset by one row, and so on.<br />

Because the loop counter is a normal variable, you can write code to change<br />

its value within the block of code between the For and the Next statements.<br />

This, however, is a very bad practice. Changing the counter within the loop<br />

can have unpredictable results. Take special precautions to ensure that your<br />

code does not directly change the value of the loop counter.<br />

A For-Next example with a Step<br />

You can use a Step value to skip some values in a For-Next loop. Here’s the<br />

same procedure as in the preceding section, rewritten to insert random numbers<br />

into every other cell:<br />

Sub FillRange2()<br />

Dim Count As Long<br />

For Count = 0 To 19 Step 2<br />

ActiveCell.Offset(Count, 0) = Rnd<br />

Next Count<br />

End Sub<br />

This time, Count starts out as 0 and then takes on a value of 2, 4, 6, and so<br />

on. The final Count value is 18. The Step value determines how the counter is<br />

incremented. Notice that the upper loop value (19) is not used because the<br />

highest value of Count after 18 would be 20, and 20 is larger than 19.<br />

Figure 10-2 shows the result of running FillRange2 when cell B2 is the<br />

active cell.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!