首页 文章

数据透视表的百分比公式

提问于
浏览
0

我想计算Excel中数据透视表的成功百分比 . 这是我的设计:

Row Labels  Count   Threshold-%

REG1        224     0.00%
    FALSE   11
    TRUE    213

REG2        213     0.00%
    FALSE   13
    TRUE    200

REG3        318     0.00%
    FALSE   3
    TRUE    315

REG4        467     0.00%
    FALSE   7
    TRUE    460

Grand Total 1222    0.00%

这是我的VBA代码:

Sub CreatePivotTable()

Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim lRow As Long
Dim pf_name As String

    pf_name = "Count of State"

    lRow = Cells(Rows.Count, 12).End(xlUp).Row

    'Data Range for Pivot Table
    SrcData = ActiveSheet.Name & "!" & Range("A1:L" & lRow).Address(ReferenceStyle:=xlR1C1)

    'Set Worksheet
    Set sht = Worksheets("Metrics")

    'Pivot Table Starting Point
    StartPvt = sht.Name & "!" & sht.Range("A3").Address(ReferenceStyle:=xlR1C1)

    'Create Pivot Cache from Source Data
    Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
        SourceType:=xlDatabase, _
        SourceData:=SrcData)

    'Create Pivot Table From Pivot Cache
    Set pvt = pvtCache.CreatePivotTable( _
        TableDestination:=StartPvt, _
        TableName:="PivotTable1")

    Set pvt = Worksheets("Metrics").PivotTables("PivotTable1")

    'Define Rows
    sht.PivotTables("PivotTable1").AddFields RowFields:=Array("Region", "State")

    'Create Count Column
    With pvt.PivotFields("State")
        .Orientation = xlDataField
        .Function = xlCount
        .Position = 1
        .NumberFormat = "0"
    End With

    'Create Calculated Column
    pvt.CalculatedFields.Add Name:="Threshold", Formula:="=SUM(True/True+False)"

    'Populate Calculated Column
    With pvt.PivotFields("Threshold")
        .Orientation = xlDataField
        .Function = xlSum
        .Position = 2
        .NumberFormat = "0.00%"
        .Caption = "Threshold-%"
    End With

    'Show Grand Totals
    pvt.ColumnGrand = True
    pvt.RowGrand = True

End Sub

我正在努力的地方是创建执行我想要的设计的公式 . 这是我用过的线:

'Create Calculated Column
    pvt.CalculatedFields.Add Name:="Threshold", Formula:="=SUM(TRUE/TRUE+FALSE)"

所有它给我的是100%的一切 . 如何访问TRUE和FALSE值,以便在正确的公式中使用它们?

另外,我只想显示每个区域的百分比总和(所以P%= TRUE /(TRUE FALSE)* 100),而不显示TRUE或FALSE的百分比总和 . 然后我想显示Grand Total行中区域百分比的平均值,如下所示:

Row Labels  Count   Threshold-%

REG1        224     95.09%
    FALSE   11
    TRUE    213

REG2        213     93.90%
    FALSE   13
    TRUE    200

REG3        318     99.06%
    FALSE   3
    TRUE    315

REG4        467     98.50%
    FALSE   7
    TRUE    460

Grand Total 1222    96.64%

1 回答

  • 0

    我想这就是你要找的东西:

    pvt.AddDataField pvt.PivotFields("State"), "Threshold", xlCount
    With pvt.PivotFields("Threshold")
        .Calculation = xlPercentOfParentRow
        .NumberFormat = "0.00%"
    End With
    

相关问题