PivotCache 是PivotTable 报告的内存缓存。 PivotTable 首先需要此内存缓存才能正常工作。
您可以从当前工作簿中的数据创建PivotCache,但它必须是新工作簿中数据透视缓存的一部分,才能基于它创建数据透视表。
由于 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 对象必须是您希望在其中创建 PivotTable 的 Workbook 的 PivotCaches 集合的一部分
编辑: 澄清一下: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