如何在数据透视表上从“总和”切换为“平均值”?

时间:2019-05-24 13:25:14

标签: excel vba pivot-table

我正在使用“ Sum”和“ Average”创建一个组合框。通过此操作,我想将数据透视表的值从总和切换为平均值,反之亦然。

因此,值字段有3列。而且我还有另一个代码,可以根据我单击的按钮使每个按钮出现。示例:如果我单击2016,则数据透视表中仅显示2016值。

如何从“总和”更改为“平均”?

Private Sub ComboBox2_Change()

    Dim pt as PivotTable
    Dim vField as PivotTable

    Set pt = ActiveSheet.PivotTables("PivotTable1")

    With ActiveSheet.ComboBox2
        Select Case ComboBox2
        Case Is = "Average"
            If pt = ("Sum of 2016") Then
                  .Caption = "Average of 2016"
                  .Function = xlAverage
            End If
            If pt = ("Sum of 2017") Then
                  .Caption = "Average of 2017"
                  .Function = xlAverage
        Case Is = "Sum"
            If pt = ("Average of 2016") Then
                  .Caption = "Sum of 2016"
                  .Function = xlSum
            End If
            If pt = ("Average of 2017") Then
                  .Caption = "Sum of 2017"
                  .Function = xlSum
            End if
        End Select
    End with
End Sub

1 个答案:

答案 0 :(得分:0)

如果您切换数据字段的Function,它将自动获得一个新名称,因此您必须在之后(而不是之前)更改名称。

您可以Select CaseCombobox.Value DataField.Caption

这是一个例子:

Private Sub ComboBox2_Change()
    Dim pt As PivotTable

    Set pt = ActiveSheet.PivotTables("PivotTable1")

    With pt.DataFields(1)
        Select Case ActiveSheet.ComboBox2.Value
        Case "Average"
            If .Caption = "Sum of 2016" Then
                .Function = xlAverage
                .Caption = "Average of 2016"
            ElseIf .Caption = "Sum of 2017" Then
                .Function = xlAverage
                .Caption = "Average of 2017"
            End If
        Case "Sum"
            If .Caption = "Average of 2016" Then
                .Function = xlSum
                .Caption = "Sum of 2016"
            ElseIf .Caption = "Average of 2017" Then
                .Function = xlSum
                .Caption = "Sum of 2017"
            End If
        End Select
    End With
End Sub

一般提示:如果使用.Function.Caption,则它属于前面的With语句,在此代码中,该语句必须是数据透视表的数据字段,而不是组合框