按计算字段对 Excel 数据透视表 Table 进行排序

Sorting an Excel Pivot Table by a calculated field

我有以下 Excel 电子表格:

     A              B              C              D    
1   Product        Category         Sale        Margin
2   Product A       Apparel          500          45%
3   Product A       Apparel          400          30%
4   Product A       Shoes            600          55%
5   Product B       Apparel          300          20%
6   Product C       Beauty           100          40%
7   Product C       Shoes            200          65%
8   Product D       Apparel          450          25%
9   Product D       Beauty           700          50%
10  Product D       Beauty           250          35%

基于这些数据,我创建了一个 Pivot Table。 在此 Pivot table 中,我添加了以下 Calculated Field 以获得利润:

   Profit = Sale * Margin

这导致以下枢轴 Table:

            Sum of Profit
Product A     1.950
Product B        60
Product C       315
Product D     1.540 

现在,我想排序这个枢轴Table降序所以它看起来像下面这样:

              Sum of Profit
Product A        1.950
Product D        1.540
Product C          315
Product B           60

对于计算字段数据透视表Table-工具中的排序选项似乎不可用。

您还有其他想法可以实现这种排序吗?

注意: 我知道我可以在源数据的 E 列 中添加利润计算。但是,与上面的简化示例相比,我的原始文件有点复杂,因此 计算字段 是不可避免的。

右键单击计算字段中的单元格 --> 排序 --> 从大到小排序。

或者你可以试试下面的代码对计算字段进行排序。

Sub SortCalculatedField()
Dim ws As Worksheet
Dim pt As PivotTable

Set ws = Sheets("Sheet1")   'This is the sheet which contains Pivot Table
Set pt = ws.PivotTables(1)
pt.PivotFields("Product").AutoSort xlDescending, "Sum of Profit", pt.PivotColumnAxis.PivotLines(1), 1
End Sub

如果行部分(分类数据)中有多个字段,数据透视表似乎无法按常规方式排序。我已经在多个 pivot table 布局中尝试过,它甚至适用于“传统”pivot table 布局。如果有必要拥有多个分类元素,我相信连接将是一种解决方法。