我有一本工作簿,包括一组数据透视表。 一套是固定的,不需要更新数据源。 另一个集合用于数据透视表,其中数据每周更新一次。
我的VBA以下:
Sub AdjustPivotDataRangeAll()
Dim PT As PivotTable, pc As PivotCache
Dim dataSheet As Worksheet, WS As Worksheet, wks As Worksheet
Dim StartPoint As Range, dataSource As Range, NewRange As String
Dim wks1 As Worksheet
Dim pt1 As PivotTable
Dim i As Long
Dim pvts As SlicerPivotTables
' Datasource workbook and worksheet
Set wkb = Workbooks("XXX.xlsb")
Set wks = wkb.Worksheets("Data")
' Worksheets in Workbook
Set WS1 = ActiveWorkbook.Worksheets("WS1")
Set PT = WS1.PivotTables("PivotTable01")
''Update Cache for PivotTable1
' Dynamically retrieve range address of data
Set dataSource = wks.Range("A1").CurrentRegion
' update pivot source and refresh
PT.ChangePivotCache ThisWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=dataSource)
PT.RefreshTable
''change pivot cache for all Pivot Tables in workbook
For Each wks1 In ActiveWorkbook.Worksheets
For Each pt1 In wks1.PivotTables
pt1.CacheIndex = Sheets("FY19-Pivot Country").PivotTables("PivotTable01").CacheIndex
Next pt1
'' Next wks1
End Sub
此代码正在更新整个工作簿中所有我的数据透视表的数据透视缓存,但是我只希望为我的两个工作表更新它。 有谁知道如何修改此代码以仅更新某些工作表?
预先感谢
答案 0 :(得分:0)
代替:
' this part is a loop through all your worksheets
For Each wks1 In ActiveWorkbook.Worksheets
For Each pt1 In wks1.PivotTables
pt1.CacheIndex = Sheets("FY19-Pivot Country").PivotTables("PivotTable01").CacheIndex
`enter code here`
Next pt1
`enter code here`
Next wks1
' replace it with this. declare the two sheets, that should be updated
set worksheet1 = ActiveWorkbook.Worksheets("worksheet1withpivot")
set worksheet2 = ActiveWorkbook.Worksheets("worksheet2withpivot")
worksheet1.CacheIndex = Sheets("FY19-Pivot Country").PivotTables("PivotTable01").CacheIndex
worksheet2.CacheIndex = Sheets("FY19-Pivot Country").PivotTables("PivotTable01").CacheIndex
代码未经测试