Export chart as image - with click of a button

2020-01-29 07:13发布

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!

标签: excel vba
2条回答
趁早两清
2楼-- · 2020-01-29 07:36

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
查看更多
可以哭但决不认输i
3楼-- · 2020-01-29 07:52

Thanks, I needed this to extract all charts in an image and it's almost midnight. Minor changes to the code above did the trick.

Sub ExportChart()
    Dim WS As Excel.Worksheet
    Dim SaveToDirectory As String

    Dim objChrt As ChartObject
    Dim myChart As Chart

    SaveToDirectory = ActiveWorkbook.Path & "\"

    For Each WS In ActiveWorkbook.Worksheets
        WS.Activate 'go there
        For Each objChrt In WS.ChartObjects
            objChrt.Activate
            Set myChart = objChrt.Chart

            myFileName = SaveToDirectory & WS.Name & "_" & objChrt.Index & ".png"

            On Error Resume Next
            Kill SaveToDirectory & WS.Name & Index & ".png"
            On Error GoTo 0

            myChart.Export Filename:=myFileName, Filtername:="PNG"
        Next
    Next

    MsgBox "OK"
End Sub
查看更多
登录 后发表回答