[英]Run-time error '1004'? Excel VBA
我的代码有问题。 我试图过滤范围以排除在K列中值等于“ March”的行,然后删除这些行。 因此,将显示除“三月”之外的所有行。 该代码可以很好地运行,直到尝试删除为止。 .Offset(1, 0).SpecialCells....
它给了我运行时错误1004
Public Sub RemoveRows()
Dim ws As Worksheet
Dim strSearch As String
Dim lRow As Long
strSearch = "March"
Set ws = Sheets("January")
With ws
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
'~~> Remove any filters
.AutoFilterMode = False
'~~> Filter, offset(to exclude headers) and delete visible rows
With .Range("K1:K" & lRow)
.AutoFilter Field:=1, Criteria1:="=*" & strSearch & "*"
.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
'~~> Remove any filters
.AutoFilterMode = False
End With
End Sub
您必须在Range语句上加点 :
Public Sub RemoveRows()
Dim ws As Worksheet
Dim strSearch As String
Dim lRow As Long
strSearch = "March"
Set ws = Sheets("January")
With ws
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
'~~> Remove any filters
.AutoFilterMode = False
'~~> Filter, offset(to exclude headers) and delete visible rows
.Range("K1:K" & lRow).AutoFilter Field:=1, Criteria1:=strSearch
.Range("K2:K" & lRow).Cells.SpecialCells(xlCellTypeVisible).EntireRow.Delete
'~~> Remove any filters
.AutoFilterMode = False
End With
End Sub
并且不需要.offset() ,只需从K2开始;
不需要内部With语句。
您不需要寻找.SpecialCells(xlCellTypeVisible)
。 只需偏移一行即可保留标题并删除。
.Offset(1, 0).EntireRow.Delete
仅可见的.AutoFilter'ed行将被删除。 您可能想要使用Application.Subtotal(103, ...)
检查是否存在要删除的行,因为在没有要删除的行的情况下尝试删除行可能会导致绕过.AutoFilter
并删除所有数据。 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.