更新Excel中多个数据透视表上的数据源
有没有简单的方法来同时更新单个Excel工作表上的多个数据透视表的数据源?
所有的数据透视表引用相同的命名范围,但我需要创build第二张工作表具有相同的数据透视表,但访问不同的命名范围。
理想情况下,我希望能够进行某种search和replace操作(就像您可以在公式中做的那样),而不是手动更新每个单独的数据透视表。
有什么build议么?
以下VBA代码将更改单个工作表上所有数据透视表的数据源。
您将需要使用新数据透视表和Data2
参数将Sheet2
参数更新为工作表的名称,以将其添加到新命名范围。
Sub Change_Pivot_Source() Dim pt As PivotTable For Each pt In ActiveWorkbook.Worksheets("Sheet2").PivotTables pt.ChangePivotCache ActiveWorkbook.PivotCaches.Create _ (SourceType:=xlDatabase, SourceData:="Data2") Next pt End Sub
假设你愿意使用VBA, 这可能是相关的。
如果您通过每个工作表上的数据透视表集合进行迭代,则应该可以使用该文章中显示的方法来修改数据源。 语法应该非常类似于使用命名范围而不是一系列单元格。
这里有一个有用的方法, 用这个VBAmacros代码dynamic地改变数据透视表的数据源范围
PivotTable
。 SourceData
属性是通过ChangePivotCache
方法设置的,该方法采用PivotCache
对象。 要创build一个,请调用ActiveWorkbook
。 PivotCaches
create
SourceType
和range
SourceData
。 最后,一旦更新,请确保调用RefreshTable
来应用更改。
这是代码中的样子。 只需将Sheet1
replace为数据源所在的位置即可。 这将自动查找工作簿中的每个数据透视表并进行更新。
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