Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';t使用VBA从Power Pivot数据模型创建Pivot表_Vba_Excel - Fatal编程技术网

Can';t使用VBA从Power Pivot数据模型创建Pivot表

Can';t使用VBA从Power Pivot数据模型创建Pivot表,vba,excel,Vba,Excel,使用Excel 2013,我正在尝试使用数据透视表.Add方法,使用现有的Power pivot模型在工作簿中创建数据透视表。我的数据透视缓存似乎有问题。以下是我迄今为止所做的工作: Dim pc As PivotCache, i As Long ' i = 1 For Each pc In ActiveWorkbook.PivotCaches Range("a" & i).Value = pc.Index Range("b" &a

使用Excel 2013,我正在尝试使用数据透视表.Add方法,使用现有的Power pivot模型在工作簿中创建数据透视表。我的数据透视缓存似乎有问题。以下是我迄今为止所做的工作:

    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
所有三个可用的数据透视缓存索引(1-3)都会发生错误

FWIW,我可以在PowerPivot功能区下手动添加数据透视表。管理>主页>数据透视表。我正试图在VBA中完成同样的事情。顺便说一句,在我开始操作刚刚创建的数据透视表之前,record宏不会记录任何内容

任何帮助都将不胜感激


谢谢…Josh虽然对你来说太晚了,但这可能会帮助其他人:

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,将XLPivotTable版本更改为14;对于Excel 2013和2016,将XLPivotTable版本更改为15。

我已运行了您的代码并尝试了多种变体以重现错误-我无法执行。我产生的唯一错误发生在透视表与前一个透视表重叠时。确保没有重叠。更改:TableDestination:=范围(“A3”)为类似“AA100”的值。。如果这起作用,那么您将知道这是导致错误的原因。可能会对您有所帮助。请尝试在代码中使用R1C1样式的范围引用,而不是A1样式。这个编辑最近为我解决了一个类似的问题。@Mike,这与这个问题无关。你试过上面的代码吗?Brian B.是对的。@MaciejLos:没有,但我通过在传递给range()对象的同一行中操作A1样式的范围地址,生成了相同的错误,并且使用我建议的方法成功地解决了这个问题。我不能代表OP的机器说话,但这次调整解决了我的类似问题。除此之外,我还使用了评论部分来建议潜在的改进,而不是回答问题。