我试图遍历已使用范围的指定列中的所有单元格,并删除其值等于变量中指定的另一个值的行。但是,无论何时我尝试使用.EntireRow.Delete的某些变体,我都会收到一条错误消息:
运行时错误' 1004': 删除Range类的方法失败
我记得这一天的工作(Excel 2007),所以我有点困惑为什么它不再工作了。 MS贬值了吗?它似乎是一段非常有用的小代码,所以我不明白为什么会这么做。
无论如何,这里是下面的代码,如果有人可以提供帮助,我会很感激。
Dim rngColumnRef As String
rngColumnRef = "$A:$A"
Dim rngDeleteValue As String
rngDeleteValue = "X"
Set tempRange = ActiveSheet.UsedRange.Columns(rngColumnRef)
For i = 1 To tempRange.Rows.Count
If ActiveCell.Value = rngDeleteValue Then
ActiveCell.EntireRow.Delete 'this is where I get the error
Else
ActiveCell.Offset(1, 0).Activate
End If
Next i
答案 0 :(得分:0)
Dim rngColumnRef As String
rngColumnRef = "$A:$A"
Dim rngDeleteValue As String
rngDeleteValue = "X"
Set tempRange = ActiveSheet.UsedRange.Columns(rngColumnRef)
For i = 1 To tempRange.Rows.Count
If ActiveCell.Value = rngDeleteValue Then
rows(i).EntireRow.Delete 'this is where I get the error
Else
ActiveCell.Offset(1, 0).Activate
End If
Next i
答案 1 :(得分:0)
看起来我在表单中有一个表(或ListObject
)未转换为范围。由于表是我试图删除的行的一部分,它根本不会让我这样做。这是我用来纠正这个的修改后的代码(或附加代码):
'New Code
Dim TableRange as ListObject 'Ideally I would place all my declarations
'up here, but I wanted to show a very
'clear, Before and After picture of the code.
For Each TableRange in ActiveSheet.ListObjects
TableRange.Unlist
Next TableRange
'End of New Code
Dim rngColumnRef As String
rngColumnRef = "$A:$A"
Dim rngDeleteValue As String
rngDeleteValue = "X"
Set tempRange = ActiveSheet.UsedRange.Columns(rngColumnRef)
For i = 1 To tempRange.Rows.Count
If ActiveCell.Value = rngDeleteValue Then
ActiveCell.EntireRow.Delete 'this is where I got the error
Else
ActiveCell.Offset(1, 0).Activate
End If
Next i