VBA数据透视表总和/计数按钮

时间:2018-07-09 13:26:03

标签: excel vba excel-vba

如标题中所述,我正在尝试创建一个按钮,以在特定数据透视表字段中的计数和总和之间交换,我可以一分为二,但是我对IF语句感到麻烦,这就是我来的原因:

Sub Count()
'
' Macro3 Macro
'

    With ActiveSheet.PivotTables("PivotTable2").PivotFields("Sum of SP/UOM")
        .Caption = "Count of SP/UOM"
        .Function = xlCount
    End With

End Sub

Sub Sum()
'
' Sum Macro
'

    With ActiveSheet.PivotTables("PivotTable2").PivotFields("Count of SP/UOM")
        .Caption = "Sum of SP/UOM"
        .Function = xlSum
    End With

End Sub

如果有人对如何实现有想法,我将非常感激!

1 个答案:

答案 0 :(得分:1)

您可以使用如下循环:

Dim pf As PivotField
For Each pf In ActiveSheet.PivotTables("PivotTable2").DataFields
    If pf.SourceName = "SP/UOM" Then
        If pf.Function = xlSum Then
            pf.Caption = "Count of SP/UOM"
            pf.Function = xlCount
        Else
            pf.Caption = "Sum of SP/UOM"
            pf.Function = xlSum
        End If
        Exit For
    End If
Next