Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA-excel paste chart as a picture

I am creating various charts from the same source. I would like to be able to cut paste with vba each chart as a picture. Does anyone know the right code?

I tried with this but it does not work:

Range("B21:C22").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'Graphs'!$B$21:$C$22")
ActiveChart.ChartType = xl3DPie
ActiveChart.ChartArea.Select
ActiveChart.ChartArea.Copy
ActiveSheet.Pictures.Paste.Select
like image 362
user1115535 Avatar asked Dec 20 '22 13:12

user1115535


2 Answers

Range("A1:A8").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'Sheet1'!$A$1:$A$8")
ActiveChart.ChartType = xlLine
ActiveChart.PlotArea.Select
ActiveChart.ChartArea.Copy


Range("A20").Select
ActiveSheet.Paste
like image 29
Jeremy Thompson Avatar answered Dec 27 '22 06:12

Jeremy Thompson


I always find copying charts confusing, but this does what you want, I think, and doesn't use any Selects, which is always nice.

Sub CreateAndCopyChart()
Dim ws As Worksheet
Dim cht As Chart

Set ws = ThisWorkbook.Worksheets("Graphs")
Set cht = ws.Shapes.AddChart.Chart
With cht
    .SetSourceData ws.Range("$B$21:$C$22")
    .ChartType = xl3DPie
    .ChartArea.Copy
End With
ws.Range("A2").PasteSpecial xlPasteValues
cht.Parent.Delete
End Sub
like image 94
Doug Glancy Avatar answered Dec 27 '22 05:12

Doug Glancy