我是 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 并从中删除每一行,但这给了我一次删除行的相同问题。有没有更好的方法来处理这个?或者,更好的是,我在定义 DeleteRange 时是否搞砸了?
谢谢!
编辑:
对不同的行集进行了一些测试,事实证明,如果它们都彼此相邻,则删除这些行没有问题。仅当行之间有间隙时才会导致运行时错误...