如何使用宏删除Excel和上移单元格中的特定行?

时间:2019-04-02 13:56:44

标签: excel vba

有人可以帮助我删除Excel中的特定行,然后通过使用宏向上移动单元格吗? 例如。我需要删除第8、14和79行。

预先感谢您的帮助

1 个答案:

答案 0 :(得分:1)

尝试:

Option Explicit

Sub test()

    Dim LastRow As Long, i As Long

    With ThisWorkbook.Worksheets("Sheet1") '<- Change sheet name if needed

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row '<- Find lastrow of column A where we assume data appears

        For i = LastRow To 1 Step -1 '<- Loop from bottom to top
            If i = 8 Or i = 14 Or i = 79 Then '<- If row is 8 or 14 or 79
                .Rows(i).EntireRow.Delete '<- Delete row
            End If

        Next i

    End With

End Sub

Pᴇʜ建议的另一种解决方案(请参见评论):

Option Explicit

Sub test()

    ThisWorkbook.Sheets("Sheet1").Range("8:8,14:14,79:79").EntireRow.Delete

End Sub

另一种解决方案:

Option Explicit

Sub test()

    With ThisWorkbook.Sheets("Sheet1")
        Union(.Rows(8), .Rows(14), .Rows(79)).Delete Shift:=xlUp
    End With

End Sub