向数据透视表添加一列,平均每年每月计数的总和

时间:2018-02-16 14:20:13

标签: excel vba excel-vba pivot pivot-table

我正在尝试在我的数据透视表中添加另一列,其中它平均显示一年内月份的总和,然后突出显示计数高于平均数的月份。

我知道有一种方法可以在数据透视表中进行平均,但不是以我正在寻找的方式进行平均,因为我正在寻找的平均值取决于计数的总和。

我还没有找到我自己做的,我不确定是否有办法做到这一点,没有它过于复杂。

PIVOT TABLE

enter image description here

CODE

Private Sub pivot()

    Dim sht             As Worksheet
    Dim pvtCache        As PivotCache
    Dim pvt             As PivotTable
    Dim StartPvt        As String
    Dim rep             As Worksheet
    Dim SrcData         As String
    Dim lstrw           As Double

    Set rep = ThisWorkbook.Worksheets("Report")

    Dim xWs As Worksheet
    Dim sheetName As String
    Application.DisplayAlerts = False
    Err.Clear
    On Error Resume Next
    Set xWs = Sheets("Pivot")
    If Err <> 0 Then
        'Do Nothing
    Else
        xWs.Delete
    End If
    Application.DisplayAlerts = True

    Set sht = Sheets.Add(, rep)
    sht.Name = "Pivot"

    SrcData = rep.ListObjects("Date_Count")
    StartPvt = sht.Name & "!" & sht.Range("A3").Address(ReferenceStyle:=xlR1C1)

    Set pvtCache = ThisWorkbook.PivotCaches.Create( _
        SourceType:=xlDatabase, SourceData:=SrcData)

    Set pvt = pvtCache.CreatePivotTable( _
        TableDestination:=StartPvt, TableName:="Date_Count Pivot")

    With sht.PivotTables("Date_Count Pivot").PivotFields("Dates")
        .Orientation = xlRowField
        .Position = 1
    End With

    sht.PivotTables("Date_Count Pivot").AddDataField ActiveSheet.PivotTables( _
        "Date_Count Pivot").PivotFields("Count"), "Sum of Count", xlSum

    sht.Range("A4").Group Start:=True, End:=True, Periods:=Array(False, False, False, _
        False, True, False, True)

    lstrw = sht.Range("A1", sht.Range("A1").End(xlDown)).Rows.Count

End Sub

0 个答案:

没有答案