Excel 中使用 VBA 控制多个透视表(pivot table)的实现

困绕很久的一个问题终于解决了。需求是在 Excel 中有很多个透视表,每个透视表的数据源是相同的,我希望让这些透视表的某个过滤条件一起联动。

比如我有三个透视表,我希望让三个表的Month选项都改成“2014-12”。查来查去发现只能用VBA实现了。

具体代码如下:

Public Sub FilterPivotTable()

Dim ORG
ORG = ActiveSheet.PivotTables("数据透视表6").PivotFields("[BRANCH_DBVIN].[ORGNAME].[ORGNAME]").CurrentPageName

With ActiveSheet.PivotTables("数据透视表12").PivotFields("[BRANCH_DBVIN].[ORGNAME].[ORGNAME]")
    .CurrentPageName = ORG
End With
End Sub

这里面“透视表6”是源数据,变量ORG存储了要变化的结果。“透视表12”是目标透视表。

如果不知道Field的名字,参考下面代码

For each pField in ActiveSheet.PivotTables("PivotTable1").PivotFields
     Debug.Print pField.Name
Next pField

Go to VBA Editor, press Ctrl+G, it will open the immediate window. It will show all the available pivot fields.Then please use the correct Pivot Field and try.

原文地址:https://www.cnblogs.com/kidoln/p/4241370.html