This doesn't work...
Sub changeData_Error()
Dim pc As PivotCache
Set pc = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Range("A1:B2"))
Excel.Sheets("Sheet1").PivotTables("PivotTable1").ChangePivotCache pc
ThisWorkbook.RefreshAll
End Sub
Have ended up with the following which seems over complicated. Can it be simplified?
Sub changeData()
':: this is the table I'd like to change the data
Dim mainP As PivotTable
Set mainP = ThisWorkbook.Sheets("Sheet1").PivotTables("PivotTable1")
':: create a new cache and set it to the new data range
Dim pc As PivotCache
Set pc = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Range("A1:B3"))
':: create a temporary pivot table
Dim pt As PivotTable
Set pt = ThisWorkbook.Sheets("Sheet1").PivotTables.Add(pc, Range("AA1"), "temptable")
':: find the index of the cache used by the temp table
Dim i As Integer
i = pt.CacheIndex
':: use the index found to redirect the main pivot at the new cache
mainP.CacheIndex = i
':: get rid of temp table
pt.TableRange2.Clear
':: this might not be needed
ThisWorkbook.RefreshAll
End Sub