Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

excel - Export chart as image - with click of a button

I'm trying to create a button that would export a chart in sheet "Graphs" as a jpeg file. This is the code I have, however it keeps on showing this error:

runtime error 424: object required

Specifically for this:

Set myChart = Graphs.ChartObjects(3).Name = "Chart4"

And here's the code

Sub ExportChart()
    Dim myChart As Chart
    Dim myFileName As String
    Set myChart = Graphs.ChartObjects(3).Name = "Chart4"
    myFileName = "myChart.jpg"
    On Error Resume Next
    Kill ThisWorkbook.Path & "" & myFileName
    myChart.Export Filename:=ThisWorkbook.Path & "" & myFileName, Filtername:="PNG"
    MsgBox "OK"
    Set myChart = Nothing
End Sub

Thanks everyone!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is this what you are trying?

Also if you are trying to save it as jpg then why a png filter? I have changed "myChart.jpg" to "myChart.png". Change as applicable.

Sub ExportChart()
    Dim objChrt As ChartObject
    Dim myChart As Chart

    Set objChrt = Sheets("Graphs").ChartObjects(3)
    Set myChart = objChrt.Chart

    myFileName = "myChart.png"

    On Error Resume Next
    Kill ThisWorkbook.Path & "" & myFileName
    On Error GoTo 0

    myChart.Export Filename:=ThisWorkbook.Path & "" & myFileName, Filtername:="PNG"

    MsgBox "OK"
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...