我在两个不同的工作表(Sheet1和Sheet2)中有两个透视表,它们从一个公共工作表(Sheet3)获取数据。在Sheet1上的数据透视表上创建切片器。如果我们转到报告连接,我们可以在列表中看到两个透视表。
现在,我正在逐个动态地更改两个数据透视表的数据透视数据源。唯一的变化是将范围扩展到包括由不同进程复制的新行。执行代码后,报表连接不再同时显示两个透视表。它只显示了一个。
使用以下代码更改pivot数据源。
Dim objwrksheet As Worksheet = mWorkBook.Worksheets(mPivotWorksheetname)
Dim objwrksheet2 As Worksheet = mWorkBook.Worksheets(mDataWorksheetname)
If Not IsNothing(objwrksheet) Then
Dim objpivottable As PivotTable = objwrksheet.PivotTables(mPivotTable)
If objpivottable IsNot Nothing Then
Dim sourceDataRange As Range = objwrksheet2.Range(mSourceRange)
Dim cache As PivotCache = mWorkBook.PivotCaches.Create(SourceType:=XlPivotTableSourceType.xlDatabase, SourceData:=sourceDataRange)
objpivottable.ChangePivotCache(cache)
objpivottable.RefreshTable()
mRetval = "Successful"
Else
mRetval = "Pivot open failed"
End If
Else
mRetval = "Worksheet open failed"
End If
预期的结果应该是,在更改了两个透视表的数据源之后,切片器报表连接应该继续在列表中显示两个透视表名称。
发布于 2019-07-12 17:49:33
这是一种通用的VBA方法:
一般情况下,您可以通过向工作簿添加新的PivotTable.SourceData
来更改PivotCache
。但如果此数据透视表包含在切片器中,则必须先通过SlicerCache.PivotTables.RemovePivotTable()
取消选中其报表连接。
如果更改了多个数据透视表的源数据,并且所有包含的数据透视表都基于相同的PivotCache
,则只能再次在切片器中重新分配它们的报表连接。
因此,在更改第一个数据透视表的源数据后,您必须为所有其他数据透视表“重用”其新的数据透视表。这种“重用”可以通过设置PivotTable.CacheIndex
来实现,只要进一步的透视表使用与第一个透视表相同的透视表字段(或其子集),它就可以工作。
备注:要使用以下代码,首先需要启用切片器的所有报表连接(因为SlicerCache.PivotTables
只返回选中的报表连接)。
Private Sub ChangeAllPivotSources()
Dim objSlicerCache As SlicerCache
Dim objPivotTable As PivotTable
Dim objPivotTables() As PivotTable
Dim i As Long
' get the slicercache, e. g. via its first pivottable:
Set objPivotTable = ActiveWorkbook.Sheets(1).PivotTables(1)
Set objSlicerCache = objPivotTable.Slicers(1).SlicerCache
' dimension array with all pivottable objects of the slicercache
ReDim objPivotTables(1 To objSlicerCache.PivotTables.Count)
' remove all pivottables from slicer's report connections
For i = objSlicerCache.PivotTables.Count To 1 Step -1
Set objPivotTables(i) = objSlicerCache.PivotTables(i)
objSlicerCache.PivotTables.RemovePivotTable objPivotTables(i)
Next i
' create new pivotcache based on a new range for the first pivottable,
' use this pivotcache for all other pivottables also
For i = 1 To UBound(objPivotTables)
If i = 1 Then
objPivotTables(i).ChangePivotCache ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=ActiveWorkbook.Sheets(3).Range("A1").CurrentRegion)
Else
objPivotTables(i).CacheIndex = objPivotTables(1).PivotCache.Index
End If
Next i
' reassign the report connections again
For i = 1 To UBound(objPivotTables)
objSlicerCache.PivotTables.AddPivotTable objPivotTables(i)
Next i
End Sub
https://stackoverflow.com/questions/56940059
复制相似问题