Home > front end >  VBA code to export chart as .jpeg file (replicate Save as Picture behavior)
VBA code to export chart as .jpeg file (replicate Save as Picture behavior)

Time:10-17

Assume I'd like to export a chart as .jpeg file. But instead of using a path directly (for example the one where my workbook is located) like here below:

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

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

    myFileName = "myChart.jpeg"
    myChart.Export Filename:=ThisWorkbook.Path & "\" & myFileName, Filtername:="jpeg"
End Sub

..I'd like a user to provide a path and name, so basically I'd like to replicate a behavior of right-click and "Save as Picture" option of the chart. I can't find any way and actually I'm not sure whether it's somehow feasible.

CodePudding user response:

Something like this?

Sub ExportChart()

    Dim objChrt As ChartObject
    Dim myChart As Chart

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

    myFileName = "myChart.jpeg"
    
    varResult = Application.GetSaveAsFilename(ThisWorkbook.Path, "jpeg (*.jpeg), ""*.jpeg""")
    
    If varResult <> False Then
        myChart.Export Filename:=varResult, Filtername:="jpeg"
    Else
        MsgBox "Export cancelled by user"
    End If
    
End Sub
  • Related