0

I have written some VBA code to insert an Embedded Picture into an Embedded Chart onto an Excel worksheet. The routine attempts to do this by copying the picture, adding an embedded chart, setting dimensions to the picture's dimensions, and then pasting the picture.

The thing is, it works with no errors when I step through it with F8 (“Debug” → “Step Into”).  The code looks simple enough, and I've experimented with placement of the Copy/Paste sequence, and nothing seems to get the picture to completed that final Paste step when running the macro.

Sub EP()
Sheet9.Shapes("Picture 2").Copy
Dim xcht As Chart: Set xcht = Sheet9.Shapes.AddChart.Chart
    With xcht
        .ChartArea.ClearContents
        .ChartArea.Width = Sheet9.Shapes("Picture 2").Width
        .ChartArea.Height = Sheet9.Shapes("Picture 2").Height
        .Paste
    End With
End Sub

It works perfectly with F8; the picture is pasted into the chart.  Just not when actually running – I ran with the green play button in the VBA editor, ran it through the macro dialog box, and ran it through a button on the worksheet.  No change in results.

What is going wrong?  How can I get this routine to run correctly by normal invocation?  Any help is appreciated.

2
  • What does happen when you run the code normally? Commented Jan 21, 2019 at 22:28
  • Do you get errors? What errors (the messages, not the numbers)? Where does the code stop, and what line is highlighted in yellow? Commented Jan 30, 2019 at 2:21

1 Answer 1

0

You need to select the chart, so the .Paste goes somewhere:

Sub EP()
  Sheet9.Shapes("Picture 2").Copy
  Dim xcht As Chart
  Set xcht = Sheet9.Shapes.AddChart.Chart
  With xcht
    .ChartArea.Select
    .ChartArea.ClearContents
    .ChartArea.Width = Sheet9.Shapes("Picture 2").Width
    .ChartArea.Height = Sheet9.Shapes("Picture 2").Height
    .Paste
  End With
End Sub

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .