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

问题描述 投票:0回答:2

我是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

当前,代码给了我

运行时错误1004:Range类的删除方法失败。

在代码末尾被注释掉的“ DeleteRange.Select”选择了正确的范围,因此我知道范围的建立是准确的。

我希望能够一次将所有要删除的行从表单中删除—在该应用程序中,要删除的行数可能会很高,我希望它不会花很长时间运行。

我在网上环顾四周,找到了一些解决方案,其中涉及迭代地遍历DeleteRange并从中删除每一行,但这给了我同样的问题,即一次删除一行。有没有更好的方法来解决这个问题?或者,更好的是,我是否搞砸了DeleteDange的定义?

谢谢!

编辑:

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

excel vba named-ranges rowdeleting
2个回答
0
投票

将“ EntireRow”属性添加到该行,如下所示:

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

0
投票

我只有在范围的侧面有一个对象(即ListObject时,才可以复制您的问题]

enter image description here

检查工作表中的数据,如果是这种情况,请使用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
© www.soinside.com 2019 - 2024. All rights reserved.