将 excel 个图表粘贴到 PowerPoint 模板中

Paste excel charts into a power point template

我对 Excel 中的 VBA 很陌生。我在 excel 中有一些图表,我想自动粘贴到 ppt 模板中。比如图表 12 进入幻灯片 7,图表 34 进入幻灯片 9,等等

我设法打开了我的模板,但在复制图表时卡住了。这是我启动它的方式,但它不起作用:

Sub CreatePowerPointTemplate()
    Dim PowerPointApp As PowerPoint.Application
    Dim cht As Excel.ChartObject

    Set PowerPointApp = CreateObject("PowerPoint.Application")

    strpath = ThisWorkbook.Path & "\My_template.pptx"
    PowerPointApp.Presentations.Open (strpath)

    ' get chart #5 and copy it into slide #7
    Set cht = Worksheets("Graphs").ChartObjects(5)
    cht.Copy
    PowerPointApp.ActivePresentation.Slides(7).Shapes.PasteSpecial(DataType:=ppPasteMetafilePicture).Select
End Sub

我认为您混合了早期和晚期绑定。这个后期绑定代码对我来说很好用。在您的代码之上添加 Option Explicit 。看看会发生什么?

Option Explicit

'~~> If you are using late binding then you need to specify the value
'~~> of the power point constant without which Excel would not know
'~~> what this is...
Private Const ppPasteMetafilePicture As Integer = 3

Sub CreatePowerPointTemplate()
    Dim PowerPointApp As Object
    Dim PowerPointPrsn As Object
    Dim cht As ChartObject
    Dim strpath As String
    
    Set PowerPointApp = CreateObject("PowerPoint.Application")

    strpath = ThisWorkbook.Path & "\My_template.pptx"
    Set PowerPointPrsn = PowerPointApp.Presentations.Open(strpath)

    ' get chart #5 and copy it into slide #7
    Set cht = Worksheets("Graphs").ChartObjects(5)
    cht.Copy
    DoEvents '<~~ Give time to excel to place the object in the clipboard
    
    PowerPointPrsn.Slides(7).Shapes.PasteSpecial DataType:=ppPasteMetafilePicture
End Sub

这是一个早期绑定示例。您需要通过 Tools->References

设置对 Microsoft Powerpoint 对象 xx.xx 库的引用

Option Explicit

Sub CreatePowerPointTemplate()
    Dim PowerPointApp As PowerPoint.Application
    Dim PowerPointPrsn As PowerPoint.Presentation
    Dim cht As ChartObject
    Dim strpath As String
    
    strpath = ThisWorkbook.Path & "\My_template.pptx"
    
    Set PowerPointApp = New PowerPoint.Application
    Set PowerPointPrsn = PowerPointApp.Presentations.Open(strpath)

    ' get chart #5 and copy it into slide #7
    Set cht = Worksheets("Graphs").ChartObjects(5)
    cht.Copy
    DoEvents
    
    PowerPointPrsn.Slides(7).Shapes.PasteSpecial DataType:=ppPasteMetafilePicture
End Sub