As EPPlus doesn't support manipulation of pivot table source ranges (more specifically, one can update the cache definition, but this update is not retained once the file is saved), I have had to resort to VBA in the template itself to update source ranges and refresh pivot tables.
There are several pivot tables each for 2 data sources stored in the file and 2 associated PivotCache objects. My goal is to update all pivot tables to new cell ranges in the 2 sources. Since I don't want to duplicate a bunch of PivotCaches to do so, I'm only creating the first one, then attempting to update subsequent pivot tables that share the dataset in question to that same cache.
Here is an excerpt for updating pivots from one of the caches ("downloads"). The rest of the function is doing the exact same thing for the 2nd cache (it's nested within the same loops, but left out for brevity).
Set downloads = ThisWorkbook.Worksheets("DLRaw")
For Each ws In ActiveWorkbook.Worksheets
For Each pt In ws.PivotTables
If Not downloadsCreated Then
Set startCell = downloads.Range("A8")
Set endCell = downloads.Range("Y" & startCell.SpecialCells(xlLastCell).Row)
Set dataRange = downloads.Range(startCell, endCell)
newRange = downloads.Name & "!" & dataRange.Address(ReferenceStyle:=xlR1C1)
pt.ChangePivotCache _
ThisWorkbook.PivotCaches.Create(xlDatabase, newRange)
Set downloadsCache = pt.PivotCache
downloadsCreated = True
Else
If pt.CacheIndex <> downloadsCache.Index Then pt.CacheIndex = downloadsCache.Index
End If
pt.RefreshTable
For Each rf In pt.RowFields
If rf.Position <> pt.RowFields.count Then
rf.ShowDetail = False
End If
Next rf
For Each cf In pt.ColumnFields
If cf.Position <> pt.ColumnFields.count Then
cf.ShowDetail = False
End If
Next cf
Next pt
Next ws
I consistently get a run-time error '1004' regarding a null entity, be thrown by the line in the Else block. Stepping through the code, I notice the CacheIndex of the newly-created pivot cache is 0, so either the downloadsCache object isn't be assigned to, or the new cache isn't being created in the first place. I do see correct values in the range variables. This behavior exists both for the excerpt above for downloads as well the 2nd cache's pivot tables.
Any ideas on where to look next, or a different approach to solving this problem if that is necessary?
If Not downloadsCreated Then, it might allow a better solution for your problem. What exactly are you trying to do with yourElsesection ?Elsewhich mean somehowdownloadsCreated = True, yes ? you ran this code before ?