Error in script which copies charts from Excel to PowerPoint

前端 未结 3 1102
渐次进展
渐次进展 2021-01-16 15:24

I am attempting to call the below Sub in order to copy given chart to a specified PowerPoint presentation. However, when I run the macro which calls this Sub, the line indic

相关标签:
3条回答
  • 2021-01-16 15:45

    It looks like the error can be attributed to how VBA handles variables across different references. (In particular, how PPT VBA handles them.) I was able to get the macro to work by actively selecting/copying the charts. I will need to do a little more research to get why variables cause problems, but at least I know how tackle the problem.

    Sub copyChart(curSlide As Slide)
        Dim chr as ChartObject
        Set chr = Sheets("CHARTSHEET").ChartObjects(1)  
        Sheets("CHARTSHEET").Select
        ActiveChart.CopyPicture
        curSlide.Shapes.PasteSpecial
    End Sub
    
    0 讨论(0)
  • 2021-01-16 15:51

    I like to use another method, I like to define an Object, then set it to the pasted Chart. Afterwards, it's much easier modifying the pasted Chart object's parameters inside PowerPoint (from Excel).

    See code below:

    Sub copyChart(curSlide As Slide)
    
    Dim chr             As ChartObject
    Dim myChart         As Object
    
    Set chr = Sheets("CHARTSHEET").ChartObjects(1)
    chr.Copy
    
    ' setting myChart object to the pasted chart (let's me later an easy way to modify it's parameters)   
    Set myChart = curSlide.Shapes.PasteSpecial(ppPasteBitmap, msoFalse) ' can change first parameter to other avaialabe formats : ppPasteGIF, ppPasteEnhancedMetafile, ppPasteOLEObject, etc.
    
    ' set different parameters for the pasted chart in PowerPoint slide
    With myChart
        .Left = 200
        .Top = 200
    End With
    
    End Sub
    

    In the code line:

    Set myChart = curSlide.Shapes.PasteSpecial(ppPasteBitmap, msoFalse)
    

    You can change the first parameter in brackets: ppPasteBitmap to many other avaialble formats (test them and see which one gives you the best result), such as: ppPasteGIF, ppPasteEnhancedMetafile, ppPasteOLEObject, etc.

    0 讨论(0)
  • 2021-01-16 16:02

    I have had a lot of trouble in recent versions of Office. 2003 and earlier didn't have this problem, 2007 and 2010 had it a bit, and 2013 and 2016 have it in spades.

    When you step through the code it works fine, but when you run it at full speed, it errors on the paste.

    It's as if the copy doesn't have time to finish finish, so when you paste the clipboard doesn't have anything in it yet to paste.

    Sometimes this helps:

    chrt.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
    DoEvents
    curSlide.Shapes.Paste
    

    DoEvents tells VBA to wait while background operations have a chance to finish up.

    0 讨论(0)
提交回复
热议问题