Hello -
I have a For Loop that is exiting early, and I cannot figure out why. Hoping maybe someone can see a flaw in my logic below.
I have data in columns A:Z. In column 27 (AA), I have a formula which determines if that row is the first occurrence of a PO Number located in the preceding column. If this is the first occurrence of that PO Number, my formula returns a value of "Y" and then the code below looks for those "Y" values and inserts a row above.
My For Loop starts at i = 2 because row 1 is headers. I'm determining the last row which has data and assigning that to the Last_Row variable. From there, the loop executes, and any time it finds a "Y" it inserts a row, and then I increment both my 'i' and 'Last_Row' variables by 1.
For some reason, my For Loop is exiting at row 1334 even though my Last_Row variable reaches 1444 as proven by the Debug statement. The code appears to be working correctly up until the point where it exits the loop, but because it exists early it's missing some "Y" values. I'm at a loss and would appreciate any help! Thanks in advance!
I have a For Loop that is exiting early, and I cannot figure out why. Hoping maybe someone can see a flaw in my logic below.
I have data in columns A:Z. In column 27 (AA), I have a formula which determines if that row is the first occurrence of a PO Number located in the preceding column. If this is the first occurrence of that PO Number, my formula returns a value of "Y" and then the code below looks for those "Y" values and inserts a row above.
My For Loop starts at i = 2 because row 1 is headers. I'm determining the last row which has data and assigning that to the Last_Row variable. From there, the loop executes, and any time it finds a "Y" it inserts a row, and then I increment both my 'i' and 'Last_Row' variables by 1.
For some reason, my For Loop is exiting at row 1334 even though my Last_Row variable reaches 1444 as proven by the Debug statement. The code appears to be working correctly up until the point where it exits the loop, but because it exists early it's missing some "Y" values. I'm at a loss and would appreciate any help! Thanks in advance!
VBA Code:
Sub Test()
With Sheet_OG
Dim i As Long
Dim Last_Row As Long
Last_Row = .Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To Last_Row
If Cells(i, 27) = "Y" Then
Rows(i).Insert Shift:=xlAbove
i = i + 1
Last_Row = Last_Row + 1
Debug.Print i & "-" & Last_Row
End If
Next i 'exits at 1334?
End With
End Sub