如何在Excel中的lastrow之后删除5行?

时间:2019-07-01 07:53:45

标签: vba

嗨,我需要删除工作表中的5行。有两组数据,一组在顶部,一组在底部。它们之间有5行。并非所有5行都是空行。所以我需要一个代码来删除行。

我尝试了以下方法,因为在第一组数据之后总是有一个空行

Const fiveRow = 5
Dim lastrow As Long, r As Range, ws As Worksheet, i As Integer
Set ws = ActiveSheet
With ws

    For i = 1 To 5
    ' This clears 5 rows
    .Cells(.Rows.Count, 1).End(xlUp).Offset(i, 0).Resize(.UsedRange.Rows.Count, 1).EntireRow.Delete
    Next i
End With

1 个答案:

答案 0 :(得分:2)

您可以使用类似以下的内容:

Option Explicit

Sub DeleteGap()

    Dim lRow As Long
    Dim ws As Worksheet
    Dim i As Long

    Set ws = Sheets("Sheet1")

    'first get the last row of the first set of data
    'then use this as referenc to delete the gap
    lRow = ws.Range("A1").End(xlDown).Row

    'if all 5 are blank - delete
'    ws.Range("A" & (lRow + 1), "A" & (lRow + 5)).EntireRow.Delete

    'if not all 5 are blank then loop through to find blank
    For i = lRow To lRow + 5
        If ws.Range("A" & i).Value = "" Then
            ws.Range("A" & i).EntireRow.Delete
        End If
    Next i

    'clear the object
    Set ws = Nothing

End Sub

根据您的要求调整"A"范围。