0
votes

I have a problem with my code. I am trying to filter the range to exclude rows where in column K the value is equal to "March" and delete those rows. So all rows except the "March" ones will be displayed. The code runs well up to the point when it is trying to delete. .Offset(1, 0).SpecialCells.... It gives me the run-time error 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
2

2 Answers

1
votes

You must put dots on your Range statements:

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

and the .offset() is not needed, just start at K2;
the internal With statement is not needed.

0
votes

You don't need to look for .SpecialCells(xlCellTypeVisible). Just offset one row to preserve your header and delete.

.Offset(1, 0).EntireRow.Delete

Only the visible .AutoFilter'ed rows will be deleted. You might want to check for the existence of rows to delete with Application.Subtotal(103, ...) as trying to delete rows when there aren't any to delete could result in bypassing the .AutoFilter and deleting all of your data..