使用VBA更新PowerPoint图表

我知道这个问题已经被问了很多次了,可惜找不到工作的解决办法。

所以,我在PowerPoint中有一个非常简单的演示文稿(只有一个幻灯片,其中一个图表是从Excel表创build的),并且需要通过VBA更新最新数据,无论是从Excel还是PowerPoint脚本运行。

首先,我尝试了PowerPoint中最明显的脚本:

Sub update1() ActivePresentation.UpdateLinks End Sub 

它似乎运行,但没有改变。 然后,我开始在Web上search解决scheme,例如, 在StackOverflow上查找以下主题 。

对于乐观繁忙的答案它运行没有错误,并给我一个输出在MessageBox,但它没有改变PowerPoint图表。

对于rinusp的回答,它给了我一个错误

运行时错误“91”:对象variables或块variables未设置

在线上

 For each sld in myPresentation.Slides 

我在PowerPoint中尝试了所有这些macros。

我也尝试了StackOverflow上的其他问题的答案,但不幸的是没有为我工作。 如果有人帮我find任何工作解决scheme,我会很高兴 – 如果VBA脚本运行,从Excel或PowerPoint中无关紧要。

提前致谢。

更新 :我正在更新我的问题,我尝试运行的代码的完整示例。 这个例子是由用户乐观Busy和rinusp在上面提到的StackOverflow主题提供的。

此代码从PowerPoint运行时给我一个错误“运行时错误'91':对象variables或块variables未设置”

 Sub update2() Dim myPresentation As PowerPoint.Presentation Dim sld As PowerPoint.Slide Dim shp As PowerPoint.Shape Dim myChart As PowerPoint.Chart For Each sld In myPresentation.Slides For Each shp In sld.Shapes If shp.HasChart Then Set myChart = shp.Chart myChart.ChartData.Activate myChart.Refresh End If Next Next End Sub 

并且此代码运行没有错误,并在消息框中提供输出,但不更新图表

 Sub update3() Dim sld As Slide, shp As Shape For Each sld In ActivePresentation.Slides For Each shp In sld.Shapes On Error Resume Next shp.LinkFormat.Update Next Next MsgBox ("Update chart") End Sub 

如果你在PowerPoint中运行macros,并且你的图表被链接,这个代码将工作。

 Sub update2() Dim myPresentation As PowerPoint.Presentation Dim sld As PowerPoint.Slide Dim shp As PowerPoint.Shape Dim myChart As PowerPoint.Chart Dim Wb As Object Dim App As Object Set myPresentation = ActivePresentation For Each sld In myPresentation.Slides For Each shp In sld.Shapes If shp.HasChart Then Set myChart = shp.Chart myChart.ChartData.Activate myChart.Refresh Set Wb = myChart.ChartData.Workbook Set App = Wb.Application Wb.Close (0) End If Next Next App.Quit End Sub