vba 将图表导出为图像 - 单击按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11939087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Export chart as image - with click of a button
提问by pufAmuf
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:
我正在尝试创建一个按钮,将工作表“Graphs”中的图表导出为 jpeg 文件。这是我的代码,但是它一直显示此错误:
runtime error 424: object required
运行时错误 424:需要对象
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!
谢谢大家!
回答by Siddharth Rout
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.
另外,如果您尝试将其另存为 jpg,那么为什么要使用 png 过滤器?我已将“myChart.jpg”更改为“myChart.png”。根据情况更改。
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
回答by Miles
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