简体   繁体   中英

Export an Excel chart WITH DATA to PowerPoint with VBA

I already have a script going to just copy a chart:

'Do the following:

Set wrkbk = ActiveWorkbook
' Load up the PowerPoint template
Set objPPT = CreateObject("Powerpoint.application")
objPPT.Visible = True
objPPT.Presentations.Open Filename:="path\to\template.pptx", ReadOnly:=msoTrue
objPPT.ActiveWindow.ViewType = 1 'ppViewSlide


' Variable defs
Dim wrksht As Worksheet
Dim chart As Object
Dim pastedChart As Object

' We're only going to copy from the current worksheet
Set wrksht = ActiveSheet
Set chart = wrksht.ChartObjects(1).chart ' We'll just use the default chart
' Now we select and copy the chart...
chart.ChartArea.Select
chart.ChartArea.Copy
With Selection
    ' Open up the active slide and paste into it
    Set pastedChart = objPPT.ActiveWindow.View.Slide.Shapes.Paste
    ' ' In earlier versions of excel, we needed to be a lot more specific ...
    ' objPPT.ActiveWindow.View.Slide.Shapes.PasteSpecial Link:=False, DataType:=wdPasteEnhancedMetafile, _
    '      Placement:=wdInLine, DisplayAsIcon:=False
    ' The default paste is a little overscaled. Scale it down.
    ' See:
    ' https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/shape-scaleheight-method-powerpoint
    pastedChart.ScaleHeight 0.9, msoFalse, msoScaleFromMiddle
 End With

This works just fine, and I also have a script that generalizes this to all worksheets in a workbook.

However, the pasted chart object still references the source Excel file. Obviously, a chart can be fully contained in PowerPoint (since you can create charts solely in there); the question is, can I do this and make the PPTX self-contained?

My best guess is that it is related to the DataTable attribute , but that's about it.

If publishing the chart as a picture which is not linked to your Excel any longer is an option for you, you might do the following with your exported chart: Insert picture -> link to file in your PowerPoint after exporting the chart like this:

Dim strFilePath, strFileName As String
Dim ChrtObj             As ChartObject

strFilePath = "path\to\template\"
strFileName = "Chart.png"  'your file name here
Set ChrtObj = Worksheets("YourSheet'sName").ChartObjects(1)
ChrtObj.Activate
ChrtObj.Chart.Export Filename:=strFilePath & strFileName, Filtername:="PNG"

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM