通过单元格值相同的工作表过滤多个数据透视表

时间:2019-06-05 21:37:34

标签: excel vba

我的最终目标是能够根据单元格值(H3)过滤同一工作表中的所有数据透视表。目前,我有与一个数据透视表完美配合的代码,我正尝试添加其余的代码。有什么建议吗?

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

'Set the Variables to be used

Dim pt As PivotTable

Dim Field As PivotField

Dim NewCat As String

  'Here you amend to suit your data

Set pt = Worksheets("Sheet1").PivotTables("PivotTable1")

Set Field = pt.PivotFields("Customer Name")

NewCat = Worksheets("Sheet1").Range("H3").Value



'This updates and refreshes the PIVOT table

With ActiveSheet.PivotTables("PivotTable1").PivotFields("Customer Name")

    .ClearAllFilters

    .PivotFilters.Add Type:=xlCaptionEquals, 

Value1:=ActiveSheet.Range("H3").Value

End With
End Sub

1 个答案:

答案 0 :(得分:1)

未经测试:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim pt As PivotTable
    Dim NewCat As String

    'if this is in the sheet1 code module you can use
    '  "Me" in place of "Worksheets("Sheet1")"
    NewCat = Worksheets("Sheet1").Range("H3").Value
    Debug.Print "Filtering on '" & NewCat & "'"
    'loop over all pivottables on the sheet
    For Each pt In Worksheets("Sheet1").PivotTables
        With pt.PivotFields("Customer Name")
            .ClearAllFilters
            .PivotFilters.Add Type:=xlCaptionEquals, Value1:=NewCat
        End With
    Next pt

End Sub