如何删除范围内的所有行?

How Can You Delete All the Rows In a Range?

我是 vba 的新手,我已经编写了下面的代码,但无法弄清楚为什么它不起作用。

Sub DataValidationDeleteWrongOrigin()
'
'Description: Goes through and deletes rows that are called out on the delete entry column.
'


'Dimension Worksheet
Dim DataValWs As Worksheet
Set DataValWs = Worksheets("Data Validation")

'Find the size of the table and store it as LastDataRow
Dim LastDataRow As Long
LastDataRow = DataValWs.Range("A5").End(xlDown).Row


'ThisRow will be the current row as the for loop goes through each row.
Dim ThisRow As Long
Dim DeleteRange As Range
Dim CurrentRow As Range
'Start the for loop from row 5
For ThisRow = 5 To LastDataRow

    'Check the Delete Entry row to see if it says Yes, delete the row. Use DeleteRange to add cells to it and delete them all at the end (much _
    faster than deleting them one at a time, and you don't have to re-find the size of the table after each row is deleted).

    If Cells(ThisRow, 16) = "Yes" Then
        If Not DeleteRange Is Nothing Then
            Set CurrentRow = DataValWs.Rows(ThisRow)
            Set DeleteRange = Union(CurrentRow, DeleteRange)
        Else
            Set DeleteRange = DataValWs.Cells(ThisRow, 16)
        End If


    End If

Next ThisRow

'DeleteRange.Select
DeleteRange.EntireRow.Delete



End Sub

目前,代码给了我

Run-time error 1004 : Delete method of Range class failed.

代码末尾附近注释掉的 "DeleteRange.Select" 选择了正确的范围,因此我知道正在准确构建范围。

我希望能够立即从 sheet 中删除所有要删除的行——在这个应用程序中要删除的行数可能会很高,而且我'我希望它不会永远 运行.

我在网上四处寻找,发现了一些解决方案,涉及迭代地通过 DeleteRange 并删除其中的每一行,但这给我带来了同样的问题,即一次删除一行。有没有更好的方法来处理这个问题?或者,更好的是,我是否在定义 DeleteRange 时搞砸了?

谢谢!

编辑:

对不同的行集进行了一些测试,结果证明,如果行都彼此相邻,则删除这些行没有问题。如果行之间有间隙,只会导致 运行 时间错误...

将"EntireRow" 属性添加到如下行:

Set DeleteRange = DataValWs.Cells(ThisRow, 16).EntireRow

只有当范围的一侧有对象(即 ListObject )时,我才能复制您的问题

检查工作表中的数据,如果是这种情况,请使用 rDelete.Delete Shift:=xlUp

假设您的数据位于 A5:P# 范围内(其中 # 是最后一行数据)使用此代码。

Sub Delete_Rows()
Dim ws As Worksheet
Dim rDelete As Range
Dim rData As Range, rRow As Range, lRw As Long

    Set ws = Worksheets("Data Validation")
    With ws
        lRw = .Range("A5").End(xlDown).Row
        Set rData = Range(.Range("A5"), Range("P" & lRw))    'adjust as required
    End With

    For Each rRow In rData.Rows
        If rRow.Cells(16) = "Yes" Then
            If rDelete Is Nothing Then
                Set rDelete = rRow

            Else
                Set rDelete = Union(rDelete, rRow)

    End If: End If: Next

    rDelete.Delete Shift:=xlUp

    End Sub