A PivotCache
是PivotTable
報告的內存緩存。該存儲器緩存對於PivotTable
首先起作用是必需的。
您可以從當前工作簿中的數據創建一個PivotCache
,但它必須是新工作簿中的PivotCaches的一部分,才能創建基於它的數據透視表。
由於PivotCache在新的Workbook.PivotCaches
中不可用,因此無法在該工作簿中創建數據透視表,因此您的代碼無法運行。
這種精細運行:
Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim pRange As Range
Dim pc As PivotCache
Dim pt As PivotTable
Set wb = Workbooks.Add
Set ws = wb.Worksheets(1)
Set pRange = ThisWorkbook.Sheets("Sheet1").Range("A1:C3")
Set pc = wb.PivotCaches.Create(xlDatabase, pRange)
Set pt = ws.PivotTables.Add(pc, Range("F2"), "MyPivotTable")
End Sub
這不起作用:
Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim pRange as Range
Dim pc As PivotCache
Dim pt As PivotTable
Set wb = Workbooks.Add
Set ws = wb.Worksheets(1)
Set pRange = ThisWorkbook.Sheets("Sheet1").Range("A1:C3")
Set pc = ThisWorkbook.PivotCaches.Create(xlDatabase, pRange) 'Cache in ThisWorkbook
Set pt = ws.PivotTables.Add(pc, Range("F2"), "MyPivotTable") 'Cache unavailable, error 5 - Invalid Procedure Call or Argument.
End Sub
此錯誤的無效參數是pc
對象。
簡而言之:PivotCache
對象需要是PivotCaches
收集Workbook
的一部分,要在其中創建PivotTable
編輯:只是爲了澄清:一個PivotCache
是在內存中的對象。它與您從中獲取數據的來源無關。無論您選擇什麼,此來源的確可以是您的第一個工作簿中的範圍,或SQL查詢的結果或CSV文件。
編輯2:一個非常基本實現 「複製」 一個pivotCache到一個新的工作簿是:
Sub CopyPivotCache()
Dim wb As Workbook
Dim InitialPivotCache As PivotCache
Dim CopyPivotCache As PivotCache
Set wb = Workbooks.Add
Set InitialPivotCache = ThisWorkbook.PivotCaches(1)
Set CopyPivotCache = wb.PivotCaches.Create(InitialPivotCache.SourceType, InitialPivotCache.SourceData)
End Sub
尼斯詳細的解釋:) –
@ShaiRado謝謝。 –
感謝您的解釋@ShaiRado,暫時我在同一個工作簿中創建Pivot表,並使用Lookup來獲取我需要的值。不過,我想知道是否可以將第一個工作簿的PivotCache複製到第二個工作簿,以便在新工作簿中創建Pivot表。 – Vikash