自动筛选错误

时间:2019-06-27 14:39:34

标签: excel vba

我想为Excel工作表创建一个自动过滤器宏,该宏将过滤掉"ballroom*"中所有不包含Column E的行,但也会保留Column E所在的任何行空

具有基本的编程知识,已经在VBA中自学了到目前为止的知识

这是我目前拥有的

Sub row_deleter()

    Dim ws As Worksheet
    Dim rng As Range
    Dim lastrow As Long

    ''setting varibles
    Set ws = ActiveSheet

    lastrow = ws.Range("E" & ws.Rows.count).End(xlUp).Row

    Set rng = ws.Range("E1:E" & lastrow)

    ''actual filter function

    With rng
        .AutoFilter field:=5, Criteria1:=IsEmpty(rng), Operator:=xlAnd, Criteria2:="=*ballroom*"
        .SpecialCells(xlCellTypeVisible).EntireRow.delete
    End With

    ''turn off filters
    ws.AutoFilterMode = False


End Sub

When I try to run this code it gives me a 1004 error saying `AutoFilter` method of range class failed, and the debug points to the `AutoFilter` line. Have tried a few things thus far with syntax etc and nothing seems to be working.

3 个答案:

答案 0 :(得分:2)

首先,让我们确保您的表具有AutoFilter。此外,您的条件不应与任何范围相关,而应与所过滤的内容相关。另外,我认为您的标准应为xlOr-单元格不能为空白并且不能容纳宴会厅。试试这个:

Sub row_deleter()

    Dim ws As Worksheet
    Dim rng As Range
    Dim lastrow As Long

    ''setting varibles
    Set ws = ActiveSheet

    lastrow = ws.Range("E" & ws.Rows.Count).End(xlUp).Row

    Set rng = ws.Range("E1:E" & lastrow)

    ''turn on autofilter if it's off
    If ws.AutoFilterMode = False Then
        ws.UsedRange.AutoFilter
    End If

    ''actual filter function
    With rng
        .AutoFilter Field:=1, Criteria1:="=", Operator:=xlOr, Criteria2:="=*ballroom*"
        .SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With

    ''turn off filters
    ws.AutoFilterMode = False

End Sub

答案 1 :(得分:1)

field:=是一个偏移量,并且只有一列作为范围。您希望将其设为field:=1

您还使用了想要xlor的xland。不能同时有一个空房间和一个带有宴会厅的房间。

.AutoFilter Field:=1, Criteria1:=IsEmpty(rng), Operator:=xlOr, Criteria2:="=*ballroom*"

答案 2 :(得分:1)

以为您有答案,并且由于您有注释(您想删除不符合条件的每一行),我对代码进行了调整,以使其更易于阅读和执行您想要的内容:

Option Explicit
Sub row_deleter()

    Dim lastrow As Long

    ''setting varibles
    'you can use a With ActiveSheet and avoid the use of ws Thought I wouldn't recommend using ActiveSheet unless you attach
    'this macro to a button on the sheet itself.
    With ActiveSheet
        lastrow = .Range("E" & .Rows.Count).End(xlUp).Row
        ''actual filter function
        .UsedRange.AutoFilter Field:=5, Criteria1:="<>", Operator:=xlOr, Criteria2:="<>*ballroom*"
        .Range("A2:A" & lastrow).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        ''turn off filters
        .AutoFilterMode = False
    End With

End Sub