I'm building an Excel 2007 workbook that contains multiple pivot tables which are all based on same pivot cache. The data source is external and retrieved by a SQL query from an Access 2007 DB. The SQL query may be changed for a purpose so a new pivot cache is created when it's modified.
I can use Pivot Table Wizard to manually steer all pivot tables to new master copy of pivot table without a problem. But I want to use VBA code to do the process to same time as I have more then 10 pvt in the workbook. So I use the Excel's macro to record a manual change. Below is what is the VBA code produced by Macro:
pvtMstrCopy is the name I give to the master pivot table. Cell E77 is inside the target pivot table which I want to change data source.Range("E77").Select ActiveSheet.PivotTableWizard SourceType:=xlPivotTable, SourceData:= _ "pvtMstrCopy" ActiveWorkbook.ShowPivotTableFieldList = True
But the problem is I can't even re-run this recorded macro. Excel report error messageRun-time error '1004' PivotTableWizard method of Worksheet class failedI add a sheet name to SourceData parameter to "Sheet1!pvtMstrCopy" and it still has the same error.
It's frustrating since I've been searching same error in various Excel forums for 2 days and I didn't find same one.
Can anyone tell me how to use VBA to change pivot table data source to another one? Thanks in advance.
Last edited by huyeote1; 06-13-2011 at 05:38 AM.
Hi huyeole1,
I recorded two macros that changed the data source for a single pivot table. See if the attached example helps you figure out how to solve your problem. I was unable to make the SourceData equal to a named range.
One test is worth a thousand opinions.
Click the * below to say thanks.
Something like:
Dim PT as PivotTable for each pt in activesheet.pivottables pt.cacheindex = sheets("Master").Pivottables("pvtMstrCopy").Cacheindex next pt
Hi Marvin,
Thanks for your help. But MS's VBA reference said ChangePivotCache method desn't work on cache that is connected to an external source.
Great, romperstomper, your method worked.
Somehow I tried to assign same index number to CacheIndex property but for no reason it failed. This time it worked. A big thank-you!
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks