Running a loop from bottom to top

时间:2016-07-11 19:20:23

标签: excel excel-vba vba

Hi I've got the following code but need it to run from bottom to top to keep the order the same from the prior sheet, but can't figure out how to do it. Everything I try seems to break the code. Thanks!

Sub Insert()
    Dim dc As Range
    With Sheets("All")
        For Each dc In Intersect(.Range("D:D"), .UsedRange)
            If dc.Value2 = 780101 Then
                dc.Resize(2, 1).EntireRow.Copy
                Sheets("780101").Rows(6).Insert Shift:=xlDown
            End If
        Next
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

我认为最简单的方法是找到最后一行,然后从那里开始工作。这应该让你接近:

Sub test()
Dim lr As Long, _
    rowCounter As Long

    With Sheets("All")
        lr = .Range("D" & Rows.Count).End(xlUp).Row
        For rowCounter = lr To 2 Step -1
            If .Cells(rowCounter, 4).Value = 780101 Then
                .Cells(rowCounter, 4).Resize(2, 1).EntireRow.Copy
                Sheets("780101").Rows(6).Insert Shift:=xlDown
            End If
        Next rowCounter
    End With
End Sub