由于这是关于AutoFilter 方法,因此我将提供这种方法,该方法涉及使用Scripting.Dictionary 对象来模拟在工作表上手动执行时将使用的过程。
在工作表上,用户将应用自动筛选,然后使用列 G 的下拉菜单“关闭”101、102 和 103 值。剩下的将被删除。在 VBA 中,我们可以抓取所有 G 列并使用不是 101、102 或 103 的值填充字典对象,并将其用作过滤操作的标准。
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](https://i.stack.imgur.com/VsCZe.png)
filterNotThree 子过程之前的数据
![filterNotThree_after](https://i.stack.imgur.com/oTmXb.png)
filterNotThree 子程序后的数据