自动过滤器没有选择表

时间:2014-10-29 18:38:31

标签: excel-vba autofilter vba excel

我想使用autofilter删除一些行而不选择表

如果工作表is选择了代码运行

如果工作表被not选中,则代码失败,我收到错误object required并突出显示Set ws = ThisWorkbook.Sheets("LI_Data_Prepped")

即使我在设置Select

时使用ws,代码也会失败

我无法弄清楚为什么这会引发错误,因为我使用数组作为标准?

由于

编辑:10-29-14

Sub DeleteSomeNamesIn_LI_Data_Prepped()
Dim ws As Excel.Worksheet
Dim lCol As Long
Dim lRow As Long
Dim cNumber As Integer

'Does NOT work like this
Set ws = ThisWorkbook.Sheets("LI_Data_Prepped").Select

'Does NOT work like this either
Set ws = ThisWorkbook.Sheets("LI_Data_Prepped")

With ws
     lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
     lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    .AutoFilterMode = False
    .Range("A1", Cells(lRow, lCol)).Cells.AutoFilter
    .Range("A1", Cells(lRow, lCol)).Cells.AutoFilter Field:=2, Criteria1:=Array("Bob", "Carol", "Ted", "Alis", "="), Operator:=xlFilterValues

    'If no rows to delete will error
     On Error Resume Next
    .UsedRange.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    .AutoFilterMode = False
    .Range("A1").End(xlDown).Offset(1).Resize(ActiveSheet.UsedRange.Rows.Count).EntireRow.Delete
    On Error GoTo 0

End With
End Sub

1 个答案:

答案 0 :(得分:0)

避免预先选择工作表:

使用Set ws = Worksheets("LI_Data_Prepped")代替

Set ws = ThisWorkbook.Sheets("LI_Data_Prepped").Select

您也可以使用Dim ws As Worksheet代替Dim ws As Excel.Worksheet