Here's a useful method adapted from Dynamically changing the range of pivot table data sources using this VBA macro
PivotTable . SourceData property that is set using the ChangePivotCache method, which accepts PivotCache . To create it, call ActiveWorkbook . PivotCaches create , which accepts SourceType and range as SourceData . Finally, after the update, be sure to call RefreshTable to apply the changes.
This is what it looks like in the code. Just replace Sheet1 wherever your data source is. This will automatically find every pivot table in your book and update it.
Sub AdjustPivotDataRange() Dim pt As PivotTable, pc As PivotCache Dim dataSheet As Worksheet, ws As Worksheet Dim startPoint As Range, dataSource As Range, newRange As String ' get worksheet with data Set dataSheet = ThisWorkbook.Worksheets("Sheet1") ' Dynamically Retrieve Range Address of Data Set startPoint = dataSheet.Range("A1") Set dataSource = dataSheet.Range(startPoint, startPoint.SpecialCells(xlLastCell)) newRange = dataSheet.Name & "!" & dataSource.Address(ReferenceStyle:=xlR1C1) ' create new PivotCache Set pc = ThisWorkbook.PivotCaches.Create( _ SourceType:=xlDatabase, _ SourceData:=newRange) ' loop through all tables in all sheets For Each ws In ActiveWorkbook.Worksheets For Each pt In ws.PivotTables ' update pivot source and refresh pt.ChangePivotCache pc pt.RefreshTable Next pt Next ws End Sub
source share