简体   繁体   English

Excel VBA导出图表

[英]Excel VBA Export chart

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. 我对VBA完全不了解,我只是想让每次保存excel文档时,将4张图表(已经在自己的标签中分开)无缝地作为PNG文件导出到预定位置。

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. 通过一些stackoverflow的数据库,我设法对要导出为CSV的工作表执行了类似的操作,但是我无法对图表进行相同的处理。

Right now thats what my VBA looks like for ThisWorkbook: 现在,这就是我的VBA在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' “下面的那个没有,我正试图从工作表“ Growth_of_10k”中获取图表以进行导出,但是它给我一个关于运行脚本超出页面的运行时错误9”

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? 知道我需要如何更改代码,以便在保存excel文档的同时将图表自动导出到与文件相同的位置(或其他预先指定的位置,没关系)?

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. 如果这是一个新手问题,很抱歉,这确实是我对VBA的首次尝试,并且在您不了解自己在做什么的情况下,使用Google谷歌搜索只能将您带到目前为止。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM