简体   繁体   中英

How come in excel2016 I cannot create 2 pivottable from 1 pivotcache

In all previous version of excel, I have no problem creating one pivot cache. Then creating several pivot tables from that pivot cache. Now I'm using the same technic in excel 2016. It just throw me error. Here is my code:

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

And the error massage is:

Run-time error '-2147417848 (80010108)':

Automation error

The object invoked has disconnected from its clients.

If I create another pivot cache for the 2nd pivot table, I won't have any problem there. But I need to generate 140 pivot tables every time, I don't want to create 140 pivot caches. That will make my book too heavy. Can someone help me figure out how I can code this in excel 2016?

My code also ran into the exact same problem after upgrading to Excel 2016.

My workaround is to create the new PivotCache, but make it temporary , by immediately re-assigning the new PivotTable's CacheIndex to the first PivotCache.

  • Upside: It works. And no workbook size increase.
  • Downside: Performance hit due creating throwaway PivotCaches.

The code:

' 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM