如何在excel2016中我无法从1个pivotcache创建2个pivottable

时间:2017-10-03 18:43:49

标签: excel-vba pivot-table vba excel

在以前的所有excel版本中,创建一个数据透视缓存都没有问题。然后从该数据透视缓存创建多个数据透视表。 现在我在excel 2016中使用相同的技术。它只是让我错误。这是我的代码:

Sub Maketbl()
 Dim Pvt As PivotTable, Pvch As PivotCache

[F:G].Clear

Set Pvch = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "Sheet1!R1C1:R6C3", Version:=6)
 '''''''''''''''''''''''
Set Pvt = Pvch.CreatePivotTable(TableDestination:= _
        "Sheet1!R1C6", DefaultVersion:=6)
With Pvt

        .AddFields RowFields:="SEASON"
        .AddDataField .PivotFields("QTY"), "Sum of QTY", xlSum
End With
''''''''''''''''''''''''''
Set Pvt = Pvch.CreatePivotTable(TableDestination:= _
        "Sheet1!R10C6", DefaultVersion:=6)
With Pvt
        .AddFields RowFields:="ITEM"
        .AddDataField .PivotFields("QTY"), "Sum of QTY", xlSum
End With

End Sub

错误按摩是:

  

运行时错误'-2147417848(80010108)':

     

自动化错误

     

调用的对象已与其客户端断开连接。

如果我为第二个数据透视表创建另一个数据透视缓存,那么我就不会有任何问题。但我每次都需要生成140个数据透视表,我不想创建140个数据透视表。这将使我的书太沉重。有人可以帮我弄清楚如何在excel 2016中编写代码吗?

1 个答案:

答案 0 :(得分:0)

升级到Excel 2016后,我的代码也遇到了完全相同的问题。

我的解决方法是创建新的PivotCache,但使其成为临时,立即将新的数据透视表的CacheIndex重新分配给第一个PivotCache。

  • 上行:它有效。而且没有增加工作簿的大小。
  • 下行:由于创建一次性PivotCaches而导致性能下降。

代码:

' First PivotTable

Set pivotTable1 = ThisWorkbook.PivotCaches.Create(...).CreatePivotTable(...)

' Second PivotTable, same SourceData, but create a new cache as workaround

Set pivotTable2 = ThisWorkbook.PivotCaches.Create(...).CreatePivotTable(...)

' Make pivotTable2 use pivotTable1's PivotCache

pivotTable2.CacheIndex = pivotTable1.PivotCache.Index

' At this point, after pivotTable2's CacheIndex is re-assigned, the 2nd
' PivotCache is no longer in use, and Excel/VBA removes it automatically.