从现有的数据透视缓存创建数据透视



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

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

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

'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"))

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

利用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"))

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

最新更新