You can use a Step value to skip some values in a For-Next loop. Here’s the same procedure as in the preceding section, rewritten to insert random numbers into every other cell:
Sub FillRange()
Dim Count As Long
For Count = 1 To 100 Step 2
ActiveCell.Offset(Count – 1, 0) = Rnd
Next Count
End Sub
This time, Count starts out as 1 and then takes on a value of 3, 5, 7, and so on. The final Count value is 99. The Step value determines how the counter is incremented.
This chapter introduces looping via the BadLoop example, which uses a GoTo statement. Here’s the same example, which is available on this book’s Web site, converted into a good loop by using the For-Next structure:
Sub FillRange()
Dim StartVal As Long
Dim NumToFill As Long
Dim CellCount As Long
StartVal = InputBox(“Enter the starting value: “)
NumToFill = InputBox(“How many cells? “)
For CellCount = 1 To NumToFill
ActiveCell.Offset(CellCount – 1, 0) = _
StartVal + CellCount – 1
Next CellCount
End Sub