簡體   English   中英

Excel VBA數據透視表緩存方法錯誤

[英]Excel VBA pivot table cache method error

我正在嘗試執行一個宏,該宏基本上從動態范圍創建數據透視表,然后利用此數據。

數據透視表保存在工作表中,每次執行宏時,它都會刪除該工作表中的數據透視表,然后更新數據范圍並使用新范圍再次生成數據透視表。

但是,嘗試生成緩存的部分代碼會導致錯誤:

“無效的過程調用或參數”。

起初它失敗了,所以我添加了一段刷新現有(我認為是)的緩存。 但是我仍然收到提到的錯誤。

代碼如下。

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

嘗試使用以下代碼設置PivotTablePivotCache

'Determine the data range you want to pivot
SrcData = Rng.Address(False, False, xlA1, xlExternal)

'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
            SourceData:=SrcData)

'Create Pivot table from Pivot Cache
Set pvt = sht.PivotTables.Add(PivotCache:=pvtCache, TableDestination:=sht.Range("A3"), _
            TableName:="PivotTable1")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM