Background
I have a spreadsheet of ticket allocations for an event. On each row of the spreadsheet is a name and the number of tickets allocated.
To keep using the For...Next
loop, you could do:
For r = LastRow To 1 Step -1
surname = Cells(r, surnameCol).Value
tickets = Cells(r, ticketCol).Value
If (Not (Len(surname) = 0)) Then
Cells(r, targetCol).Value = surname
For x = 1 To tickets - 1
Cells(r + x, 1).EntireRow.Insert
Cells(r + x, targetCol).Value = surname
Next x
LastRow = LastRow + tickets - 1
End If
Next r
Any time that you want to insert or delete rows on a Worksheet
from inside a loop, it's usually better to start at the end and work backwards. This means that you don't have to adjust your loop index in most cases
The compiler interperets the 'For' Loop construct differently, and uses different assembly calls to place the temporary variable into CPU cache, so after each iteration it doesn't need to go back out to RAM to read the variable, it can just grab it from the cpu's cache. This is by design to increase performance, thats why 'For' loops are generally faster than 'While' loops. The limit variable for the 'for' loop still lives in memory, but its not reading it during each iteration. So if you change the variable used to originally set the upper bound, your loop will still run to the original bound you set it to. While loops check its exit clause at each iteration, and does not cache is variable. Generally 'For' loops should be used when you have a set amount of iterations, as opposed to the while loop when you are not sure how many times you will need to loop, and need more dynamic control.
This is by design in VB. The limit of a for loop is calculated only once and saved in a temporary variable, just before the start of the loop. So if you change the value of the variables from which it calculates the limit, the temp variable is not affected. While this has the unexpected effect you encountered, it has the plus that the limit is only calculated once, so any methods used in this calculation is only entered once, potentially doing the loop faster.