我正在尝试设置一些VBA代码,允许我使用1个切片器控制多个数据透视表(和数据源)。
在过去,我只需要实现控制1个额外切片器的VBA代码,但现在我正在尝试将其设置为控制2个切片器并遇到问题。
这是我过去用来控制1个切片器的代码:
作为一个模块:
Public PrevCat As String
在ThisWorkbook中:
Private Sub Workbook_Open()
PrevCat = Sheet27.Range("O5").Value
End Sub
主要代码:
Option Explicit
Private Sub Worksheet_Calculate()
Application.ScreenUpdating = False
Dim pt As PivotTable
Dim Field As PivotField
Dim NewCat As String
NewCat = Sheet27.Range("O5").Value
If NewCat <> PrevCat Then
Application.EnableEvents = False
Set pt = Sheet27.PivotTables("Pivot Match 2")
Set Field = pt.PivotFields("Region")
With Field
.ClearAllFilters
On Error Resume Next
.CurrentPage = NewCat
On Error GoTo 0
End With
pt.RefreshTable
PrevCat = NewCat
Application.EnableEvents = True
End If
Application.ScreenUpdating = True
End Sub
就像我说的,这段代码非常适合控制1个额外的切片器。但是,我需要代码来控制2个切片器。我所做的就是添加一个额外的If语句,但它似乎不起作用:
Option Explicit
Private Sub Worksheet_Calculate()
Application.ScreenUpdating = False
Dim pt As PivotTable
Dim Field As PivotField
Dim NewCat As String
NewCat = Sheet27.Range("O5").Value
If NewCat <> PrevCat Then
Application.EnableEvents = False
Set pt = Sheet27.PivotTables("Pivot Match 2")
Set Field = pt.PivotFields("Region")
With Field
.ClearAllFilters
On Error Resume Next
.CurrentPage = NewCat
On Error GoTo 0
End With
pt.RefreshTable
PrevCat = NewCat
Application.EnableEvents = True
End If
If NewCat <> PrevCat Then
Application.EnableEvents = False
Set pt = Sheet27.PivotTables("Pivot Match 3")
Set Field = pt.PivotFields("Region")
With Field
.ClearAllFilters
On Error Resume Next
.CurrentPage = NewCat
On Error GoTo 0
End With
pt.RefreshTable
PrevCat = NewCat
Application.EnableEvents = True
End If
Application.ScreenUpdating = True
End Sub
关于如何让它发挥作用的任何想法?