如何确保PivotCache正常工作?

我试图通过VBA在Excel中创build一个数据透视表,但我不能为了我的生活找出为什么这个代码不工作。 它不会抛出任何错误 – 只是没有创build数据透视表。 我在其他程序中使用完全相同的代码没有问题(显然replace本地variables)。 我已经确认我的源数据是正确定义的。 我唯一的领导是在执行创build数据透视caching之后,它显示了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 

无论上面的代码如何工作,我都无法做到。 所以,我只是决定使用录音机并修改输出。 这里有一些工作代码:

  '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格式的源数据范围也破坏了这个代码。