即使值不存在,也要排除过滤器中的值

时间:2018-03-22 18:20:09

标签: vba excel-vba excel

我有很多文件需要循环播放。在每个文件中,我必须过滤掉特定的值。

实施例。 我必须过滤掉数字1, 3, 5, 7, 9并保留其他所有内容

开始

1
2
3
4
9
11
15

结果

2
4
11
15

我提出了这个代码,但事实证明它没有用,因为它不起作用

    Rows("1:1").Select
    Selection.AutoFilter
    wkb.Sheets("temp").Range("$A$1:$AC$72565").AutoFilter Field:=9, Criteria1:="Main"
    wkb.Sheets("temp").Range("$A$1:$AC$72565").AutoFilter Field:=10, Criteria1:="C"
    wkb.Sheets("temp").Range("$A$1:$AC$72565").AutoFilter Field:=11, Criteria1:="N"

'this part of the code is where I try to exclude values
    wkb.Sheets("temp").Range("$A$1:$AC$72565").AutoFilter Field:=1, Criteria1:=Array("<>1", "<>3", "<>5", "<>7", "<>9")

2 个答案:

答案 0 :(得分:1)

考虑逆逻辑,只过滤你想要删除的内容吗?

Sub test()

Dim rng As Range

Set rng = wkb.Sheets("temp").Range("$A$1:$AC$72565")

rng.AutoFilter Field:=1, Criteria1:=Array("1", "3", "5", "7", "9"), Operator:=xlFilterValues
' In case your data has header used Offset(1,0) to preserve the header on the first row
rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
rng.AutoFilter

End Sub

答案 1 :(得分:0)

试试这个(代码中所有必要的注释):

Sub filter()
'declaration of variables
Dim numbers(5) As Long, cell As Range, number As Variant
'fill this array accordingly to your needs (notee that you'd have to change array size in declaration
numbers(0) = 1
numbers(1) = 3
numbers(2) = 5
numbers(3) = 7
numbers(4) = 9
'here we loop through all cells in frist row, this lenghty formule is for finding last fill column in first row
For Each cell In Range(Cells(1, 1), Cells(1, Cells(1, Columns.Count).End(xlToLeft).Column))
    'here we loop through specified numbers to filter out these values
    For Each number In numbers
        If number = cell.Value Then
            'if match is found, clear the cell and leave the loop
            cell.Value = ""
            Exit For
        End If
    Next
Next
End Sub