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