3 回答

TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊
記住目標(biāo)是刪除不匹配的行;自動(dòng)篩選只是幫助實(shí)現(xiàn)該目標(biāo)的一種工具。如果自動(dòng)篩選不能滿足您的需求,請(qǐng)選擇其他方法??紤]:
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
在這里,我們選擇要處理的數(shù)據(jù)塊(不包括標(biāo)題行)。宏向下掃描該塊的第7列,并刪除任何不符合條件的行。
剩下的將是101、102和103。

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
由于這是關(guān)于AutoFilter方法的,因此我將提供這種方法,其中涉及使用Scripting.Dictionary對(duì)象來(lái)模擬在工作表上手動(dòng)執(zhí)行該過(guò)程。
在工作表上,用戶將應(yīng)用“自動(dòng)篩選”,然后使用G列的下拉菜單“關(guān)閉” 101、102和103值。剩下的將被刪除。在VBA中,我們可以獲取所有G列,并使用非101、102或103的值填充字典對(duì)象,并將其用作過(guò)濾操作的標(biāo)準(zhǔn)。
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貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
我在做類似的事情,但在兩個(gè)領(lǐng)域,這種語(yǔ)法對(duì)我有用:
myrange.AutoFilter Field:=7, Criteria1:="<>101", Operator:=xlAnd, Criteria2:="<>102", Operator:=xlAnd
希望能幫助到你。
- 3 回答
- 0 關(guān)注
- 928 瀏覽
添加回答
舉報(bào)