Excel 按同一工作表中的单元格值筛选多个透视表

Excel 按同一工作表中的单元格值筛选多个透视表,excel,vba,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 'He

我的最终目标是能够基于单元格值(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
未经测试:

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

非常感谢你,蒂姆,这真是太棒了,正是我想要的!!!