我有这个非常简单的VBA代码,我用它来查找列中的某些文本并擦除整行。但由于某种原因,每次运行它都会给我这个错误:运行时错误'424':需要对象
任何线索?
<input id="inp" value="ABCDEFG">
<div id="display"></div>
答案 0 :(得分:3)
当您删除行时,您可以更改SrchRng指向的行:最终您可能会到达已删除其所有单元格的位置,因此它不再是有效的范围引用。一旦达到该点,任何对SrchRange的引用都将引发错误。
您可以在循环时收集要删除的行,然后在结尾删除所有行:
Sub DeleteText()
Dim c As Range
Dim sArray(1 To 4) As String, i As Long
sArray(1) = "TEXT 1"
sArray(2) = "TEXT 2"
sArray(3) = "TEXT 3"
sArray(4) = "TEXT 4"
Dim SrchRng As Range, rngDelete As Range
Set SrchRng = ActiveSheet.Range("A1", ActiveSheet.Range("A65536").End(xlUp))
For i = 1 To 4
Do
'NOTE: use LookAt to ensure you're not making a partial match
' Unless you want that...
Set c = SrchRng.Find(What:=sArray(i), LookIn:=xlValues, lookat:=xlWhole)
If Not c Is Nothing Then
c.Value = "" '<< so it's not found again
'build up a range of cells to delete
If rngDelete Is Nothing Then
Set rngDelete = c
Else
Set rngDelete = Application.Union(c, rngDelete)
End If
End If
Loop While Not c Is Nothing
Next i
'delete any found rows
If Not rngDelete Is Nothing Then rngDelete.EntireRow.Delete
End Sub