2017-06-20 36 views
0

我已经在工作表'sourcebook.xlsx'中的工作表'sourceSheet'中创建了一个Pivot缓存。我试图在工作表'destinSheet'中的不同工作簿'destinBook.xlsx'中创建一个Pivot表。在一个工作簿中的透视表缓存,另一个工作簿中的透视表

Dim pCache As PivotCache 
Dim pTable As PivotTable 
Dim pRange As Range 

Module2.hc_book.Activate 
Set pRange = ActiveSheet.Range(hc_pidCol & "1:" & hc_pidCol & hc_lastRow) 

Set pCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, pRange) 
Module2.mt_book.Activate 
Set tempSheet = Worksheets.Add 
tempSheet.Select 
Set pTable = ActiveSheet.PivotTables.Add(pCache, Range("A1"), "MyPivotTable") 

该代码给了我最后一行错误 - “无效的过程调用或参数”,我设置pTable。该代码可以在同一张表单中正常工作。所以,请让我知道我犯的错误。

回答

1

A PivotCachePivotTable报告的内存缓存。该存储器缓存对于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 
+0

尼斯详细的解释:) –

+0

@ShaiRado谢谢。 –

+0

感谢您的解释@ShaiRado,暂时我在同一个工作簿中创建Pivot表,并使用Lookup来获取我需要的值。不过,我想知道是否可以将第一个工作簿的PivotCache复制到第二个工作簿,以便在新工作簿中创建Pivot表。 – Vikash

相关问题