I have this macro below that deletes rows based upon criteria. My issue is that if there is not any rows of data that meet the deletion criteria, it throws an error. How do I get this to not throw an error if there are no rows to delete?
Public Sub Deletion()
Dim wksData As Worksheet
Dim lngLastRow As Long
Dim rngData As Range
'Set references up-front
Set wksData = ThisWorkbook.Worksheets("Tester")
'Identify the last row and use that info to set up the Range
With wksData
lngLastRow = .Range("V" & .Rows.Count).End(xlUp).Row
Set rngData = .Range("V2:V" & lngLastRow)
End With
Application.DisplayAlerts = False
With rngData
'Apply the Autofilter method to the first column of
'the range, using xlOr to select either
.AutoFilter Field:=22, _
Criteria1:="Delete"
'Delete the visible rows while keeping the header
.Offset(1, 0).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Rows.Delete
End With
Application.DisplayAlerts = True
'Turn off the AutoFilter
With wksData
.AutoFilterMode = False
If .FilterMode = True Then
.ShowAllData
End If
End With
'Let the user know the rows have been removed
MsgBox "All Rows were removed. Thank you!"
End Sub
CodePudding user response:
There is no need to use Range.SpecialCells
when deleting the visible cells. A filtered range reference automatically only returns the visible cells.
Public Sub Deletion()
Dim rngData As Range
With ThisWorkbook.Worksheets("Tester")
Set rngData = .Range("V2", .Cells(.Rows.Count, "V").End(xlUp))
End With
With rngData.CurrentRegion
.AutoFilter Field:=22, Criteria1:="Delete"
.Offset(1).EntireRow.Delete
rngData.Parent.ShowAllData
End With
End Sub
Here is how to use Range.SpecialCells
:
Sub DeleteVisibleRows(Target As Range)
On Error Resume Next
Set Target = Target.SpecialCells(xlCellTypeVisible)
If Err.Number = 0 Then Target.EntireRow.Delete
On Error GoTo 0
End Sub