I have created a Pivot Cache in (say)Workbook 'sourceBook.xlsx' in sheet 'sourceSheet'. I am trying to create a Pivot table in a different workbook 'destinBook.xlsx' in sheet 'destinSheet'.
Dim pCache As PivotCache
Dim pTable As PivotTable
Dim pRange As Range
Module2.hc_book.Activate
Set pRange = ActiveSheet.Range(hc_pidCol & "1:" & hc_pidCol & hc_lastRow)
Set pCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, pRange)
Module2.mt_book.Activate
Set tempSheet = Worksheets.Add
tempSheet.Select
Set pTable = ActiveSheet.PivotTables.Add(pCache, Range("A1"), "MyPivotTable")
The code is giving me error in the last line - "Invalid procedure call or argument", where I am setting the pTable. The code works fine for destination in the same sheet. So, please let me know where I am making the mistakes.
A
PivotCache
is the memory cache for aPivotTable
report. This memory cache is needed for thePivotTable
to function in the first place.You could create a
PivotCache
from data in the current workbook, but it would have to be part of the PivotCaches in the new workbook, in order to create a PivotTable based of off it.Since the PivotCache is not available in the new
Workbook.PivotCaches
, you cannot create a PivotTable in that workbook of off it and that's why your code doesn't run.This runs fine:
This does not work:
The invalid argument for this error is the
pc
object.In short:
PivotCache
object needs to be part of thePivotCaches
collection of theWorkbook
where you wish to create thePivotTable
EDIT: Just to clarify: A
PivotCache
is an in memory object. It has nothing to do with the source where you got the data from. This source can indeed be the range in your first workbook, or the results of a SQL query, or a CSV-file, whatever you choose.EDIT 2: A very basic implementation of "copying" a pivotCache to a new workbook would be: