【发布时间】:2017-07-25 03:42:00
【问题描述】:
我正在尝试执行一个宏,它基本上从动态范围创建一个数据透视表,然后利用这些数据。
数据透视表保存在工作表中,每次执行宏都会删除该工作表中的数据透视表,然后更新数据范围并使用新范围再次生成数据透视表。
但是,尝试生成缓存的部分代码会导致错误:
“无效的过程调用或参数”。
起初它失败了,所以我添加了一个刷新现有(我认为是)缓存的片段。但我仍然收到提到的错误。
代码如下。
Sub Weeks_Coverage_Calc()
'Creates a pivot table to calculate stock weeks coverage for every item
Dim sht As Worksheet
Dim Activesht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim lastRow As Integer
Dim Rng As Range
Dim Row As Range
'Clear the worksheet for pivot table
Set sht = ActiveWorkbook.Sheets("Weeks Coverage")
For Each pvt In sht.PivotTables
pvt.PivotSelect "", xlDataAndLabel, True
Selection.Delete Shift:=xlToLeft
Next pvt
'Set Transfer sheet as active sheet
Set Activesht = ActiveWorkbook.Sheets("Transfer")
'Determine the dynamic range
lastRow = Activesht.Range("B1000000").End(xlUp).Row
Set Rng = Activesht.Range("B4:AF" & lastRow)
'Determine the data range you want to pivot
SrcData = ActiveSheet.Name & "!" & Rng.Address(ReferenceStyle:=xlR1C1)
'Initialize the cell to start the table
StartPvt = sht.Name & "!" & sht.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Refresh pivot cache
For i = 1 To Worksheets("Weeks Coverage").PivotTables.Count
Worksheets("Weeks Coverage").PivotTables(i).PivotCache.Refresh
Next i
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable1")
'Add fields to Pivot Table
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Item ID")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Stok"), "Sum of Stok", xlSum
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Sales"), "Sum of Sales", xlSum
【问题讨论】:
-
应该是
SrcData = ActiveSht.Name而不是SrcData = ActiveSheet.Name
标签: excel caching pivot-table vba