Excel VBA自动filter只有三个

在我的数据分析( 第一个问题 )的连续传奇中,我想要删除所有部门(字段7)不是101,102或103(名称已被更改以保护无辜者)的行。 数据中有大约100个部门,因此使用Criteria1:=Array("104", "105", "106",等是不切实际的。

我想要做这样的事情:

myrange.AutoFilter Field:=7, Criteria1:="<>101", Operator:=xlOr, Criteria2:="<>102", Operator:=xlOr, Criteria3:="<>103"

但Excel不能识别2个以上的标准。 我可以添加一个帮助列,并通过每行(如果101,102或103,然后value =是)运行macros,过滤掉所有剩下的东西,但我将它保存为最后采取。

有没有办法让Autofilter Criteria1不等于数组? 就像是:

myrange.AutoFilter Field:=7, Criteria1:="<>" & Array("101", "102", "103")

记住目标是删除不匹配的行; AutoFilter只是帮助实现目标的一个工具。 如果AutoFilter不能满足您的需求,请select其他方法。 考虑:

 Sub AllBut() Dim rTable As Range, r As Range Dim rDelete As Range Set rTable = Selection Set rDelete = Nothing For Each r In rTable.Columns(7).Cells v = r.Value If v <> "101" And v <> "102" And v <> "103" Then If rDelete Is Nothing Then Set rDelete = r Else Set rDelete = Union(r, rDelete) End If End If Next If Not rDelete Is Nothing Then rDelete.EntireRow.Delete End Sub 

这里我们select要处理的数据块(不包括标题行)。 该macros扫描该块的第7列,并删除任何不符合条件的行。

剩下的就是101,102和103了。

由于这是关于AutoFilter方法的 ,所以我将提供这种方法,包括使用Scripting.Dictionary对象来模仿如果在工作表上手动执行的过程。

在工作表上,用户将应用AutoFilter,然后使用列G的下拉菜单closures101,102和103的值。 剩下的将被删除。 在VBA中,我们可以抓取所有列G,并填充一个不是101,102或103的字典对象,并将其用作filter操作的标准。

 Sub filterNotThree() Dim d As Long, dDELs As Object, vVALs As Variant Set dDELs = CreateObject("Scripting.Dictionary") With Worksheets("Sheet6") If .AutoFilterMode Then .AutoFilterMode = False With .Cells(1, 1).CurrentRegion 'grab all of column G (minus the header) into a variant array vVALs = .Resize(.Rows.Count - 1, 1).Offset(1, 6).Value2 'populate the dictionary object with the values that are NOT 101, 102, or 103 For d = LBound(vVALs, 1) To UBound(vVALs, 1) Select Case vVALs(d, 1) Case 101, 102, 103 'do not add Case Else 'not a match, add it to the delete list 'the AutoFilter criteria needs to be text ' so we set the Keys as text and the Items as numbers dDELs.Item(CStr(vVALs(d, 1))) = vVALs(d, 1) End Select Next d 'check to make sure there is something to filter on If CBool(dDELs.Count) Then 'filter on the dictionary keys .AutoFilter field:=7, Criteria1:=dDELs.keys, Operator:=xlFilterValues 'delete the visible rows (there has to be some) .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).EntireRow.Delete End If End With If .AutoFilterMode Then .AutoFilterMode = False End With dDELs.RemoveAll: Set dDELs = Nothing End Sub 

filterNotThree_before
filterNotThree子过程之前的数据

filterNotThree_after
filterNotThree子程序后的数据

我正在做类似的事情,但对于两个领域,这个语法为我工作:

 myrange.AutoFilter Field:=7, Criteria1:="<>101", Operator:=xlAnd, Criteria2:="<>102", Operator:=xlAnd 

希望能帮助到你。