Paste Excel Chart into Powerpoint using VBA

前端 未结 2 435
自闭症患者
自闭症患者 2020-12-03 00:28

I\'m trying to create an excel macro that copies charts displayed on an excel sheet, and pastes them (paste special) into a PowerPoint. The problem I\'m having is how do I p

2条回答
  •  误落风尘
    2020-12-03 00:53

    Code with function for plotting 6 charts from Excel to PPT

    Option Base 1
    Public ppApp As PowerPoint.Application
    
    Sub CopyChart()
    
    Dim wb As Workbook, ws As Worksheet
    Dim oPPTPres As PowerPoint.Presentation
    Dim myPPT As String
    myPPT = "C:\LearnPPT\MyPresentation2.pptx"
    
    Set ppApp = CreateObject("PowerPoint.Application")
    'Set oPPTPres = ppApp.Presentations("MyPresentation2.pptx")
    Set oPPTPres = ppApp.Presentations.Open(Filename:=myPPT)
    ppApp.Visible = True
    Set wb = ThisWorkbook
    Set ws = wb.Sheets(1)
    
    i = 1
    
    For Each shp In ws.Shapes
    
        strShapename = "C" & i
        ws.Shapes(shp.Name).Name = strShapename
        'shpArray.Add (shp)
        i = i + 1
    
    Next shp
    
    Call Plot6Chart(oPPTPres, 2, ws.Shapes(1), ws.Shapes(2), ws.Shapes(3), ws.Shapes(4), ws.Shapes(5), ws.Shapes(6))
    
    End Sub
    Function Plot6Chart(pPres As Presentation, SlideNo As Long, ParamArray cCharts())
    
    Dim oSh As Shape
    Dim pSlide As Slide
    Dim lLeft As Long, lTop As Long
    
    Application.CutCopyMode = False
    Set pSlide = pPres.Slides(SlideNo)
    
    For i = 0 To UBound(cCharts)
    
        cCharts(i).Copy
        ppApp.ActiveWindow.View.GotoSlide SlideNo
        pSlide.Shapes.Paste
        Application.CutCopyMode = False
    
    
        If i = 0 Then ' 1st Chart
            lTop = 0
            lLeft = 0
        ElseIf i = 1 Then ' 2ndChart
            lLeft = lLeft + 240
        ElseIf i = 2 Then ' 3rd Chart
            lLeft = lLeft + 240
        ElseIf i = 3 Then ' 4th Chart
            lTop = lTop + 270
            lLeft = 0
        ElseIf i = 4 Then ' 5th Chart
            lLeft = lLeft + 240
        ElseIf i = 5 Then ' 6th Chart
            lLeft = lLeft + 240
        End If
    
        pSlide.Shapes(cCharts(i).Name).Left = lLeft
        pSlide.Shapes(cCharts(i).Name).Top = lTop
    
    Next i
    
    Set oSh = Nothing
    Set pSlide = Nothing
    Set oPPTPres = Nothing
    Set ppApp = Nothing
    Set pPres = Nothing
    
    End Function
    

提交回复
热议问题