首页 > 解决方案 > 使用隐藏单元格删除 VBA 中的值

问题描述

我正在尝试从 Excel 中的表中删除所有“0”值。我编写了以下代码,但它返回方法 'Range of object'_Worksheet' 失败。我需要做什么来解决这个问题?

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

标签: excelvbadelete-row

解决方案


正如@BigBen 所指出的,您错误地引用了带有变量的范围。我还删除了SpecialCells设置最后一行时:

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

推荐阅读