3 回答
TA贡献1982条经验 获得超2个赞
记住目标是删除不匹配的行;自动筛选只是帮助实现该目标的一种工具。如果自动筛选不能满足您的需求,请选择其他方法。考虑:
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
在这里,我们选择要处理的数据块(不包括标题行)。宏向下扫描该块的第7列,并删除任何不符合条件的行。
剩下的将是101、102和103。
TA贡献1783条经验 获得超4个赞
由于这是关于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
TA贡献1802条经验 获得超4个赞
我在做类似的事情,但在两个领域,这种语法对我有用:
myrange.AutoFilter Field:=7, Criteria1:="<>101", Operator:=xlAnd, Criteria2:="<>102", Operator:=xlAnd
希望能帮助到你。
- 3 回答
- 0 关注
- 805 浏览
添加回答
举报