我在使用不同数据源的不同Excel工作表上有2个不同的数据透视表。它们都具有可以过滤的“样式”列。当我在一个数据透视表上过滤样式时,我希望另一个数据透视表自动(或通过按钮)过滤那些相同的选定样式。
我目前正在处理在其他论坛上找到的这段代码。在VBA的“对象”部分中,我有:
Sub ChangePivotFilter()
Dim WS As Excel.Worksheet
Dim aWB As Excel.Workbook
Dim myPivot As Excel.PivotTable
Dim myPivotField As Excel.PivotField
Set aWB = ActiveWorkbook
For Each WS In aWB.Worksheets
For Each myPivot In WS.PivotTables
Set myPivotField = Nothing
On Error Resume Next
Set myPivotField = myPivot.PivotFields(“Style”)
myPivotField.CurrentPage = “Style”
Next myPivot
Next WS
End Sub
在VBA的“模块”部分中,我有:
Sub Button1_Click()
Dim s$
Application.EnableEvents = False
If Target.Name = "PivotTable1" Then
With ThisWorkbook.PivotTables
Let s = .Item("PivotTable1").PivotFields("Style").CurrentPage
.Item("PivotTable2").PivotFields("Style").ClearAllFilters
.Item("PivotTable2").PivotFields("Style").CurrentPage = s
End With
Else
With ThisWorkbook.PivotTables
Let s = .Item("PivotTable2").PivotFields("Style").CurrentPage
.Item("PivotTable1").PivotFields("Style").ClearAllFilters
.Item("PivotTable1").PivotFields("Style").CurrentPage = s
End With
End If
Application.EnableEvents = True
End Sub