Mitchell Lawlor
Mitchell Lawlor

Reputation: 45

Delete values in VBA with hidden Cells

I am trying to delete all "0" values from a table in excel. I have the following code written but it returns that Method 'Range of object'_Worksheet' failed. What do I need to do to fix this?

Sub Macro()

Dim ws As Worksheet          
''Set reference
Set ws = ThisWorkbook.Worksheets("Compressed Schedule results")

''Apply Filter
    ws.Range("A2:B2").AutoFilter Field:=1, Criteria1:="0"
 lrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).SpecialCells(xlCellTypeVisible).Row
''Delete the Rows
Application.DisplayAlerts = False
ws.Range("A2:lrow").SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True


ws.ShowAllData



End Sub

Upvotes: 0

Views: 246

Answers (1)

BruceWayne
BruceWayne

Reputation: 23283

As @BigBen noted, you are referencing a range with a variable incorrectly. I also removed the SpecialCells when setting the last row:

Sub Macro()
Dim ws As Worksheet
Dim lRow As Long
''Set reference
Set ws = ThisWorkbook.Worksheets("Compressed Schedule results")
lRow = ws.Cells(Rows.Count, "A").End(xlUp).Row  
''Apply Filter  
ws.Range("A2:B2").AutoFilter Field:=1, Criteria1:="0"
''Delete the Rows
Application.DisplayAlerts = False
ws.Range("A2:A" & lRow).SpecialCells(xlCellTypeVisible).EntireRow.Delete
Application.DisplayAlerts = True
ws.ShowAllData
End Sub

Upvotes: 1

Related Questions