【问题标题】:Create Pivot from already existing PivotCache从现有的 PivotCache 创建 Pivot
【发布时间】:2017-01-19 17:11:11
【问题描述】:

我想根据用于在另一个工作簿中创建另一个数据透视表的数据创建一个新的数据透视表。

我已经意识到以下几点: 1.) 打开保存数据的工作簿 2.) 将包含数据透视表的工作表复制到新的工作簿中

现在我想从现有的数据透视表中访问缓存,并在同一工作簿的不同工作表上创建一个新的。因此我使用以下代码: 设置 input_pivot_sheet = input_workbook.Worksheets("Worksheetbblabla")

'Select right Pivot Table
Set pivot_table = input_pivot_sheet.PivotTables(2)

'Create new Excel file
Set temp_excel_workbook = Workbooks.Add
Application.SheetsInNewWorkbook = 1

'Create supportive Pivot by copying content from old file to new file
input_pivot_sheet.Copy After:=temp_excel_workbook.Sheets(1)
Set pivot_cache = pivot_table.PivotCache
'Create new Pivot out of this pivot...
Set worksheet_1 = temp_excel_workbook.Sheets(1)
new_pivot_table = pivot_cache.CreatePivotTable(worksheet_1.Range("A1"))

此代码失败,因为我收到运行时错误 5:此行中的过程调用或参数无效:

new_pivot_table = pivot_cache.CreatePivotTable(worksheet_1.Range("A1"))

如何访问另一个数据透视表中的数据并在另一个工作表上绘制新的数据透视表?

【问题讨论】:

  • Set new_pivot_table = pivot_cache.CreatePivotTable(worksheet_1.Range("A1"))。由于数据透视表是一个对象,因此您必须通过Set 对其进行分配。
  • 想是这样,但是缺少Set 会给出错误91,而不是错误5。
  • 您不能使用具有不同父级的数据透视缓存,即工作簿。
  • Cyboashu-你成功了。您不能在其他工作簿中创建数据透视表;但您可以在同一工作簿的新工作表中创建它们。我修改了我的代码,请参阅下面的评论。

标签: excel vba pivot pivot-table


【解决方案1】:

利用 cyboashu 的评论(你可以在问题帖子中找到它作为评论)我稍微调整了我的代码:

     'Switch to right Worksheet - Attention if "blablabka" is renamed...!!!!
    Set input_pivot_sheet = input_workbook.Worksheets("blabla")

    'Create new Excel file
    Set temp_excel_workbook = Workbooks.Add
    Application.SheetsInNewWorkbook = 1

    'Create supportive Pivot by copying content from old file to new file
    input_pivot_sheet.Copy After:=temp_excel_workbook.Sheets(1)

    'Close old file & newly created one
    input_workbook.Close
    temp_excel_workbook.SaveAs Filename:=temp_excel_file_name
    temp_excel_workbook.Close

    'Open new Excel... - not performant...
    Set temp_excel_workbook = Workbooks.Open(temp_excel_file_name)

    'Select right Pivot Table
    Set pivot_table = temp_excel_workbook.Sheets(2).PivotTables(2)
    Set pivot_cache = pivot_table.PivotCache
    'Create new Pivot out of this pivot...
    Set worksheet_1 = temp_excel_workbook.Sheets(1)
    new_pivot_table = pivot_cache.CreatePivotTable(worksheet_1.Range("A1"))

现在我可以添加字段和行了。谢谢大家!

【讨论】:

    猜你喜欢
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 2021-09-10
    相关资源
    最近更新 更多