根据日期值对数据透视表中的行项目进行分组

时间:2016-07-03 14:18:09

标签: excel-vba vba excel

我有一个这样的工作表:

NAME    DATE        CITY
John    05/12/1978  Detroit
Mark    09/11/1987  Detroit
Chris   18/10/1982  Detroit
Dave    20/04/1990  New York

My Pivot Table看起来像这样(带行字段):

[-] Detroit
    John
    Mark
    Chris
[-] New York
    Dave

我想写一个宏来根据日期对名称进行分组:

[-] Detroit
    [-] Dates before 04/05/1981
        John
    [-] Dates after 04/05/1981
        Mark
        Chris
[-] New York
    [-] Dates before 04/05/1981
    [-] Dates after 04/05/1981
        Dave

要创建“之前”组,我正在尝试这样做:

Dim PvtTbl As PivotTable
Dim City As PivotItem
Dim MyDate As PivotItem
Dim r As Range

Set PvtTbl = Worksheets("Worksheet1").PivotTables("Dynamic table1")

For Each City In PvtTbl.PivotFields("CITY").PivotItems
    For Each MyDate In City.PivotFields("DATE").PivotItems      ' ERROR HERE
        If MyDate.Value < DateValue("04/05/1981") Then
            If Not r Is Nothing Then
                Set r = Union(r, MyDate.DataRange)
            Else
                Set r = MyDate.DataRange
            r.Select
            End If
        End If
        r.Group
    Next
Next

End Sub

有人可以指出我正确的方向吗?

0 个答案:

没有答案