Loop to last row while adding rows

我们两清 提交于 2019-12-12 04:31:50

问题


My loop is breaking a few thousand lines before the last row.

Let's say last row is up to 12000, its looping until 9800.

For i = 2 To lastrow
    If ws.Cells(i, 2).Value = "4" Then
        Rows(i).Insert
        Range("E" & i).Value = ws.Cells(i + 1, 5)
        i = i + 1
        lastrow = lastrow + 1
    End If  
Next i

回答1:


@Nathan_Sav makes a good point. I'm not sure how the i = i + 1 and Next i interact with each other. I'd try it this way:

i = 2
While i <= lastrow
    If ws.Cells(i, 2).Value = "4" Then
        Rows(i).Insert
        Range("E" & i).Value = ws.Cells(i + 1, 5)
        i = i + 1
        lastrow = lastrow + 1
    End If
    i = i + 1
Wend

Without data to test this against, or the rest of the code, it's hard to be sure this will work ... so let me know how you get on.



来源:https://stackoverflow.com/questions/43765057/loop-to-last-row-while-adding-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!