如何从excel表中引用pivot字段?

时间:2015-07-06 20:35:12

标签: excel vba excel-vba

我正在尝试编写将从Excel表创建数据透视表的代码,并且我不断收到运行时错误,这些错误会指责我无效的数据透视表字段名称。

Sub pivotTracking()

Dim wsTracking As Worksheet
Dim tblTracking As ListObject
Dim pcTracking As PivotCache
Dim ptTracking As PivotTable
Dim ptDestination As Range

Set wsTracking = ActiveWorkbook.Sheets("Tracking")
Set tblTracking = wsTracking.ListObjects("tblTracking")

   'Create the cache from the data range
    Set pcTracking = ActiveWorkbook.PivotCaches.Create( _
        SourceType:=xlDatabase, _
        SourceData:=wsTracking.Range("tblTracking").Address _
        )

    'Set table destination range
    Set ptDestination = wsTracking.Range("P2")

    'Create the Pivot table
    Set ptTracking = wsTracking.PivotTables.add( _
        PivotCache:=pcTracking, _
        TableDestination:=ptDestination, _
        TableName:="Pivot2" _
        )

    ActiveWorkbook.ShowPivotTableFieldList = True
        'Debug.Print ptTracking.PivotFields(1).Name
            'Returns nothing

    'Add fields
    With ptTracking

        With .PivotFields(Date) 'Quotes here don't help :-/
             .Orientation = xlColumnField
             .Position = 1
        End With

        With .PivotFields(TechNbr)
             .Orientation = xlRowField
             .Position = 1
        End With

        With .PivotFields(status)
             .Orientation = xlRowField
             .Position = 2
        End With

        With .PivotFields(status)
             .Orientation = xlDataField
             .Position = 1
             .caption = "TechTracker"
             .Function = xlCount
        End With

End With

ActiveWorkbook.ShowPivotTableFieldList = False

End Sub 

我尝试过以多种方式引用表格范围,我尝试过使用硬引用,我甚至尝试为每个数据透视字段声明变量。有谁可以帮我纠正以下代码?

1 个答案:

答案 0 :(得分:0)

Date是一种数据类型(适用于日期),而不是其他数据透视表