2017-07-25 141 views
0

我知道這個問題已經被多次詢問和回答,但不幸的是找不到工作解決方案。使用VBA更新PowerPoint圖表

因此,我在PowerPoint中有一個非常簡單的演示文稿(只有一張幻燈片,其中一張圖表是從Excel表創建的),並且需要通過VBA更新最近的數據,無論是從Excel還是PowerPoint腳本運行。

首先,我想最明顯的腳本從PowerPoint:

Sub update1() 
ActivePresentation.UpdateLinks 
End Sub 

它似乎運行,但不需要做任何改變。然後我開始在網上搜索解決方案,例如,找到以下topic on StackOverflow

對於Optimistic Busy的回答,它運行時沒有錯誤,並在MessageBox中給我一個輸出,但它在PowerPoint圖表中沒有任何變化。

的答案被rinusp它給了我一個錯誤

運行時錯誤「91」:對象變量或帶塊變量未設置

上線

For each sld in myPresentation.Slides 

我在PowerPoint中嘗試了所有這些宏。

我也嘗試過從StackOverflow的其他問題的答案,但不幸的是沒有爲我工作。如果有人幫助我找到任何工作解決方案,我會很高興 - 如果VBA腳本運行,從Excel或PowerPoint中無關緊要。

在此先感謝。

UPDATE:我正在更新我的問題,我已經嘗試運行的代碼的完整示例。這個例子是由上面提到的StackOverflow主題的用戶Optimistic Busy和rinusp提供的。

從PowerPoint運行時,該代碼給我一個錯誤「運行時錯誤‘91’:對象變量或帶塊變量未設置」

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 
+0

你好,你可以發佈你正在努力工作的完整代碼。該錯誤似乎與沒有引用您正在與之交互的對象有關。 –

+0

@RyanWildry,我用完整的代碼示例更新了我的問題。 – Hasek

回答

1

如果您在powerpoint中運行宏並且鏈接了圖表,則此代碼將起作用。

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 
+0

謝謝,它的工作原理。如果我想用另一個表格(在另一個Excel文件中)的數據更新圖表並使用與原始結構類似的結構,您還可以解釋如何修改它? – Hasek

+0

@Hasek,你可以在另一個Excel文件中。 –