无法使用VBA从Power Pivot数据模型创build数据透视表

使用Excel 2013,我试图使用PivotTables.Add方法使用现有的Power Pivot模型在工作簿中创build数据透视表。 我的PivotCache似乎有问题。 这是我迄今为止所做的:

Dim pc As PivotCache, i As Long ' i = 1 For Each pc In ActiveWorkbook.PivotCaches Range("a" & i).Value = pc.Index Range("b" & i).Value = pc.CommandText i = i + 1 Next 

产生这个:

 1 Model 2 Model 3 Model 

但是,运行下面抛出一个运行时错误:

  Range("a1").Select ActiveSheet.PivotTables.Add _ PivotCache:=ActiveWorkBook.PivotCaches(1), _ TableDestination:=Range("A3") 

错误是:

 Run-time Error '1004': Application-defined or object-defined error 

所有三个可用的PivotCache索引(1-3)发生错误。

FWIW,我可以在PowerPivotfunction区下手动添加数据透视表。 pipe理>首页>数据透视表。 我试图在VBA中完成同样的事情。 顺便说一句,loggingmacros不logging任何东西,直到我开始操纵我刚刚创build的数据透视表。

任何帮助将不胜感激。

谢谢…乔希

尽pipe对于你来说太迟了,这可能会帮助别人:

 Sub xlPivotTable() Dim pc As PivotCache Dim pt As PivotTable 'Create PivotCache from PowerPivot Data Model Set pc = ThisWorkbook.PivotCaches.Create(SourceType:=xlExternal, _ SourceData:=ThisWorkbook.Connections("ThisWorkbookDataModel"), _ Version:=xlPivotTableVersion15) 'Create PivotTable from PivotCache Set pt = pc.CreatePivotTable(TableDestination:=ActiveCell, _ DefaultVersion:=xlPivotTableVersion15) Set pt = Nothing Set pc = Nothing End Sub 

将Excel 2010的xlPivotTableVersion更改为14,对Excel 2013和2016更改15。