Converting Do Loop to For Loop

 

Given a pseudo code Do Loop

 And the For…Next loop format

Counter = 1

Do as long as Counter is <= 10
     Print counter
     Counter = Counter + 1
End loop

For loopVar = IntValue to StopValue Step IncrValue
 
     one or more VB instructions
 
Next loopVar

 

When writing a For..Next loop you must keep in mind the three things the For..Next statement has built in

  1. The loop control variable is initialized

  2. The loop control variable is compared to the stop value

  3. The loop control variable is incremented by the step value

     

For Counter = 1 to 10 Step 1
        Print counter
Next Counter

 

Therefore you must not have any code in the For…Next block of code to be executed that alters the value of the loop control variable.

For Counter = 1 To intStopValue
        Print Counter
        Counter += 1<----   DO NOT DO THIS
Next Counter


 
Also the loop control variable must not be the same variable as the stop value variable

For Counter = 1 To Counter  <----   DO NOT DO THIS
        Print Counter
Next Counter

Instead

For Counter = 1 To StopVariable
        Print Counter
Next Counter