Excel VBA-筛选数据透视表中的特定数据

时间:2019-03-20 19:46:41

标签: excel vba

我尝试使用似乎对

上的海报有帮助的代码

Excel VBA - Privot table filter multiple criteria

但是我继续遇到以下错误:无法获取PIvotTable类的PIvtoFields属性。

Sub FilterPivotItems()

    Dim PT          As PivotTable
    Dim PTItm       As PivotItem
    Dim FiterArr()  As Variant

    ' use an array to select the items in the pivot filter you want to keep visible
    FiterArr = Array("MC. Santa Clara", "MC. Plaza Américas", "MC. El Frutal")

    ' set the Pivot Table
    Set PT = ActiveSheet.PivotTables("PivotTable4")

    ' loop through all Pivot Items in "Value" Pivot field
    For Each PTItm In PT.PivotFields("Value").PivotItems
        If Not IsError(Application.Match(PTItm.Caption, FiterArr, 0)) Then ' check if current item is not in the filter array
            PTItm.Visible = True
        Else
            PTItm.Visible = False
        End If
    Next PTItm

End Sub

我该怎么办?

1 个答案:

答案 0 :(得分:0)

在了解了类的属性之后,我终于找到了想要的东西。

Sub filterpivot()


Dim pi As PivotItem
Dim pt As PivotTable
Dim first As String
Dim second As String
Dim third As String
Dim fourth As String

first = Range("a26").Value
second = Range("a27").Value
third = Range("a28").Value
fourth = Range("a29").Value

Set pt = Worksheets("Lowest Scores").PivotTables("PivotTable4")

    With pt.PivotFields("Nombre conjunto")
        For Each pi In pt.PivotFields("Nombre conjunto").PivotItems
        
        
            If pi.Name = first Or pi.Name = second Or pi.Name = third Or pi.Name = fourth Then
                pi.Visible = True
            Else
                pi.Visible = False
            End If
        Next pi
    End With


End Sub

这将基于特定单元格值应用过滤器。我很抱歉,如果已经有人在做这项工作,我正处于工作紧要关头,需要答案。