I know absolutely nothing about VBA, I'm just trying to have 4 charts (that are already separated in their own tabs) be seamlessly exported as PNG files to a prespecified location every time I save an excel document.
Going through some of stackoverflow's database I managed to do something similar with a worksheet that I wanted to export as a CSV, but I can't manage to do the same for my charts.
Right now thats what my VBA looks like for ThisWorkbook:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.DisplayAlerts = False
Application.ScreenUpdating = False
ThisWorkbook.Worksheets("CSV Monthly Update").Copy
ActiveWorkbook.SaveAs Filename:="CSV Monthly Update.csv", FileFormat:=xlCSVWindows
ActiveWorkbook.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
'This above part works well'
'The one below doesn't, I'm trying to get the chart from Worksheet "Growth_of_10k" to be exported but it gives me a Runtime error 9 about runscript being out of page'
Sub ExportChart()
Dim objChrt As ChartObject
Dim myChart As Chart
Set objChrt = Sheets("Growth_of_10k").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
Any idea how I would need to change the code so that the chart is exported automatically to the same location as the file (or another pre-specified location, it doesn't matter) at the same time as I save the excel document?
I'm sorry if this is a newbie question, this is really my very first endeavor with VBA and googling can only get you so far when you don't understand what you're doing.
Thanks a ton in advance.
A chart sheet is different from a chartobject embedded on a worksheet.
Thisworkbook.Sheets("Chart1").Export _
Filename:=ThisWorkbook.Path & "\" & myFileName, Filtername:="PNG"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.