自动过滤器不起作用

时间:2018-02-14 02:14:55

标签: excel vba excel-vba

我有一个代码,它有一个命令按钮,用于从外部文件中检索其记录。 每次单击命令按钮时,它将删除所有记录并再次粘贴。但它允许用户输入带有" OFM"," KH"和"衣领&袖带"因此它不会删除这些行。

但是,我的自动过滤器代码无法正常工作,因为它仍然删除行" OFM"和" KH""

 Rows.Count).CurrentRegion.SpecialCells(xlCellTypeVisible).AutoFilter 
 field:=1, Criteria1:="<>OFM", Operator:=xlOr, Criteria2:="<>KH"

代码:

Sub July()
Dim arr, c, b(), n&
Application.ScreenUpdating = False
Worksheets("July 2018").Range("A4").AutoFilter
Workbooks.Open "C:\Users\sophia.tan\Desktop\MasterPlanData.xlsx", 0, 1
arr = Sheets("Excel").UsedRange
ActiveWorkbook.Close 0
c = Array(0, 2, 13, 14, 7, 8, 11, 1, 9, 10, 16, 17, 20, 22, 15, 30, 27, 28, 
29, 3, 4, 39)
d = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 
20, 21, 23)
ReDim b(1 To UBound(arr), 1 To 23)

For i = 2 To UBound(arr)
If arr(i, 13) >= DateSerial(Year:=2018, Month:=7, Day:=1) And arr(i, 12) <= 
DateSerial(Year:=2018, Month:=7, Day:=31) Then
    n = n + 1
    For j = 1 To UBound(c)
        b(n, d(j)) = arr(i, c(j))
     Next
 End If
Next


With Worksheets("July 2018")

.Range("A4:W" & 
Rows.Count).CurrentRegion.SpecialCells(xlCellTypeVisible).AutoFilter 
field:=13, Criteria1:="<>Collar & Cuff"
.Range("A4:W" & 
Rows.Count).CurrentRegion.SpecialCells(xlCellTypeVisible).AutoFilter 
field:=1, Criteria1:="<>OFM", Operator:=xlOr, Criteria2:="<>KH"
.Range("A4:W" & Rows.Count).CurrentRegion.Offset(1, 
0).SpecialCells(xlCellTypeVisible).ClearContents
.Range("A4:W" & Rows.Count).Resize(UBound(b, 1), UBound(b, 2)) = b
.AutoFilter.ShowAllData
.Range("A4").CurrentRegion.Sort key1:=Range("G3"), order1:=xlAscending, 
Header:=xlYes
.Range("A4").Select
End With
Call Fabrication
Application.ScreenUpdating = 1
End Sub

1 个答案:

答案 0 :(得分:1)

您的双标准一字段AutoFilter逻辑存在缺陷。当某些东西不是 KH 时,它可以是 OFM ,当某些东西不是 OFM 时,它可以是 KH 。我相信你想要过滤不是 KH 而不是 OFM

tldr;

你需要xlAnd,而不是xlOr。

'...

With Worksheets("July 2018")
    If .AutoFilterMode Then .AutoFilterMode = False
    With .Range("A4").CurrentRegion
        .AutoFilter Field:=13, Criteria1:="<>Collar & Cuff"
        .AutoFilter Field:=1, Criteria1:="<>OFM", Operator:=xlAnd, Criteria2:="<>KH"   '<~~ THIS RIGHT HERE
        With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
            If CBool(Application.Subtotal(103, .Cells)) Then
                .SpecialCells(xlCellTypeVisible).ClearContents
            End If
        End With
        .Cells.Sort key1:=.Columns("G"), Order1:=xlAscending, Header:=xlYes
    End With
    '...
    .AutoFilter.ShowAllData
    .Range("A4").Select
End With