如何确保PivotCache正常工作?

时间:2017-08-23 21:04:10

标签: excel vba pivot-table

我正在尝试通过VBA在Excel中创建一个数据透视图,但我不能为我的生活弄清楚为什么这段代码不起作用。它没有抛出任何错误 - 只是没有创建数据透视表。我在其他程序中使用了完全相同的代码而没有问题(显然替换了局部变量)。我已经确认我的源数据已正确定义。我唯一的领先是在执行数据库缓存的创建后,它显示PvtCache = Nothing。

Option Explicit
Sub Create_Report()

Dim sht_Break_Data As Worksheet
Dim sht_Num_Breaks_Pvt As Worksheet

Dim tab_name As String
Dim lrow_Src As Long
Dim lcol_Src As Long

Dim rng_Pvt_Source As Range
Dim PvtStart As Range
Dim PvtCache As PivotCache
Dim Pvt As PivotTable
Dim PvtField As PivotField
Dim PvtName As String

    Set_Global_Variables

    'Get last row and column of Source Data Tab
    With sht_Source_Data
        lrow_Src = .Cells(Cells.Rows.Count, 1).End(xlUp).Row
        lcol_Src = .Cells(1, Cells.Columns.Count).End(xlToLeft).Column

    'Set source data range for pivots
        Set rng_Pvt_Source = .Range(.Cells(1, 1), .Cells(lrow_Src, lcol_Src))
    End With

'=======================================Create Pivot for Number of Breaks==========================================='
    'Create sheet for Number of Breaks Pivot
    'If the given tab name already exists, contents are deleted. If not, it is created
    With ThisWorkbook
        tab_name = "Num of Breaks Pivot"
        If SheetExists(tab_name, ThisWorkbook) = True Then
            Set sht_Num_Breaks_Pvt = .Sheets(tab_name)
            On Error Resume Next
            sht_Num_Breaks_Pvt.ShowAllData 'clear any active filter
            sht_Num_Breaks_Pvt.Cells.Delete 'delete content
            Else
            .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = tab_name 'add new tab to the end
            Set sht_Num_Breaks_Pvt = .Sheets(tab_name)
        End If

        'Define pivot start location
        Set PvtStart = sht_Num_Breaks_Pvt.Cells(2, 1)

        'Create Pivot Cache from Source Data
        Set PvtCache = .PivotCaches.Create( _
            SourceType:=xlDatabase, _
            SourceData:=rng_Pvt_Source)

        'Create Pivot table from Pivot cache
        Set Pvt = PvtCache.CreatePivotTable( _
            TableDestination:=PvtStart, _
            TableName:="test")
    End With

End Sub

1 个答案:

答案 0 :(得分:0)

无论多么有意义,我都无法使用上述代码。所以,我刚决定使用录音机并修改输出。这是一些有效的代码:

    'Create pivot for Breaks w/o Remedies >30 days
    .PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        rng_rmdy_GT30.Address(, , xlR1C1, True), Version:=xlPivotTableVersion14). _
        CreatePivotTable TableDestination:=sht_rmdyGT30_Pivot.Cells(2, 1), _
        TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion14
    sht_rmdyGT30_Pivot.Activate
    Set Pvt = ActiveSheet.PivotTables("PivotTable1")

奇怪的是,没有R1C1格式的源数据范围也破坏了这段代码。