VBA:删除过滤的单元格(不是整行)

时间:2017-06-09 16:28:51

标签: excel vba excel-vba

我试图过滤细胞,然后删除那些可见的细胞。我通常可以这样做:

Option Explicit

Private Sub RemoveRecipientsWhenItemSend(Item As Outlook.mailitem)

Dim RemoveAddrList As VBA.Collection
Dim InfoAddrList As VBA.Collection

Dim Recipients As Outlook.Recipients
Dim aRecipient As Outlook.Recipient
Dim bRecipient As Outlook.Recipient

Dim i
Dim j
Dim a
Dim b

Dim info As Boolean

info = False
Set RemoveAddrList = New VBA.Collection
Set InfoAddrList = New VBA.Collection

InfoAddrList.Add "team@company.com"

RemoveAddrList.Add "member1@company.com"
RemoveAddrList.Add "member2@company.com"

Set Recipients = Item.Recipients

For i = Recipients.count To 1 Step -1

    Set aRecipient = Recipients.Item(i)

    For j = 1 To InfoAddrList.count

        Debug.Print LCase$(aRecipient.Address)
        Debug.Print LCase$(InfoAddrList(j))

        If LCase$(aRecipient.Address) = LCase$(InfoAddrList(j)) Then

            For a = Recipients.count To 1 Step -1

                'Set bRecipient = Recipients.Item(a)
                Set aRecipient = Recipients.Item(a)

                For b = 1 To RemoveAddrList.count

                    Debug.Print vbCr & " a: " & a
                    Debug.Print " LCase$(aRecipient.Address): " & LCase$(aRecipient.Address)
                    Debug.Print " LCase$(RemoveAddrList(b)): " & LCase$(RemoveAddrList(b))

                    If LCase$(aRecipient.Address) = LCase$(RemoveAddrList(b)) Then
                        'Recipients.Remove i
                        Recipients.Remove a
                        Exit For
                    End If

                Next

            Next

            Exit For

        End If
    Next
Next

End Sub


Private Sub RemoveRecipientsWhenItemSend_test()
    RemoveRecipientsWhenItemSend ActiveInspector.currentItem
End Sub

但是,这一次我是在带有数据透视表旁边的工作表上进行的,因此我得到了一个' 1004'错误,它无法进行更改,因为它会影响数据透视表。我不想删除Pivot的部分内容,只是我尝试过滤的范围。

我该怎么做?

3 个答案:

答案 0 :(得分:0)

正确的方法是,如果你不打算将计算完全转移到VBA ......就是清除单元格然后排序。删除行具有各种副作用,并且根据工作簿设置,在计算方面成本极高。

答案 1 :(得分:0)

您的数据范围应格式化为表格;我倾向于打电话给表格"数据"以及数据表中的表格" tData" (类似于工作簿中的所有表)。表的优点是不需要任何格式化代码,因为当新行添加到表中而你不需要范围(" A1:Z"& lastrow)等时,它会向下传播!

确定过滤列10并删除单元格值= 2

的所有行
Dim tbl as ListObject

Set tbl = Sheets("Data").ListObjects("tData")                'create tbl ref
With tbl
    .Range.AutoFilter Field:=10, Criteria1:="2"              'apply filter
    .DataBodyRange.SpecialCells(xlCellTypeVisible).Delete    'delete results
    .Range.AutoFilter Field:=10                              'remove filter
End With
set tbl = Nothing                                            'kill tbl ref

答案 2 :(得分:0)

很显然,您想在这些单元格上使用Range.Delete Shift:=xlShiftUp而不是整行。因此,只需像平常一样过滤目标范围,然后使用SpecialCells(xlCellTypeVisible)获取要删除的范围。

请注意,由于在过滤模式下Excel仅允许您删除整行,因此请确保在删除过滤器后执行Range.Delete