excel vba – 如果filter更改,则对数据透视表进行sorting

有没有办法自动sorting数据透视表每次数据透视表给定的filter更改?

我想在第三列按降序排列数据透视表。 该表的filter每个月都会更新一次。 因此,我不想手动每次sorting。

这是我手动做vba代码。

Sub example() ' ' example Macro ' Range("BO12").Select 'change period filter from "3" to "4" With ActiveSheet.PivotTables("PivotTable2").PivotFields("Period") .PivotItems("3").Visible = True .PivotItems("4").Visible = False End With 'sort the table in descending order by the values in the 3rd column ActiveSheet.PivotTables("PivotTable2").PivotFields("Channel").AutoSort _ xlDescending, "Sum of Shares", ActiveSheet.PivotTables("PivotTable2"). _ PivotColumnAxis.PivotLines(3), 1 End Sub 

有没有办法让这个自动化?

问题表中的图像:

在这里输入图像说明

我试图无济于事。

 Private Sub SortTables(ByVal Target As Range) ' ' SortTables Macro ' ' Range("D12").Select If Target.Name = "PivotTable3" Then ActiveSheet.PivotTables("PivotTable3").PivotFields("Channel").AutoSort _ xlDescending, "Sum of Shares", ActiveSheet.PivotTables("PivotTable3"). _ PivotColumnAxis.PivotLines(3), 1 End If End Sub 

尝试下面的代码,它将根据PivotFields("Period")对数值进行Sort ,其中.PivotItems("3") (稍后可以轻松修改以适应您的需要)。

 Option Explicit Sub example() Dim PivTbl As PivotTable Dim PivFld As PivotField Dim RngKey1 As Range ' set the Pivot Table to an object Set PivTbl = ActiveSheet.PivotTables("PivotTable2") 'change period filter from "3" to "4" With PivTbl With .PivotFields("Period") .PivotItems("3").Visible = True .PivotItems("4").Visible = False End With ' set "Period" to a PivotField Object Set PivFld = .PivotFields("Period") ' set the SortRange to PivotItem "3" of PivotField "Period" Set RngKey1 = PivFld.PivotItems("3").DataRange ' sort the Pivot Table's values in escending order, according to PivotItem "3" column PivFld.PivotItems("3").DataRange.Sort key1:=RngKey1, Order1:=xlDescending, Type:=xlSortValues, Orientation:=xlTopToBottom End With End Sub