[英]Copy and paste an excel chart with a VBA macro in word
I'm aware that my question may sound/be trivial, but I couldn't find the solution anywhere...and I'm exhausted. 我知道我的问题听起来很简单,但我找不到任何解决方案...我已经筋疲力尽了。
I'm writing a macro to automatize a report generation in Word. 我正在编写一个宏来自动在Word中生成报告。 At some stage, I need to insert some chart, which is located as a chartsheet from excel...but no way.
在某个阶段,我需要插入一些图表,该图表位于excel的图表表中,但是没有办法。 Here's my code
这是我的代码
Sub copy_pic_excel()
Dim xlsobj_2 As Object
Dim xlsfile_chart As Object
Dim chart As Object
Set xlsobj_2 = CreateObject("Excel.Application")
xlsobj_2.Application.Visible = False
Set xlsfile_chart = xlsobj_2.Application.Workbooks.Open("path_to_file.xlsx")
Set chart = xlsfile_chart.Charts("sigma_X_chart")
chart.Select
chart.Copy
With Selection
.PasteSpecial Link:=False, DataType:=wdPasteEnhancedMetafile, _
Placement:=wdInLine, DisplayAsIcon:=False
End With
End Sub
But it keeps showing the error message: "Run-time error '5342': The specified data type is unavailable." 但是它一直显示错误消息:“运行时错误'5342':指定的数据类型不可用。”
I have no clue why it isn't pasting the chart. 我不知道为什么它没有粘贴图表。 I thought to use the clipboard via 'MSForms.DataObject', but i seems that it only works with text (or strings).
我本来想通过“ MSForms.DataObject”使用剪贴板,但是我似乎只适用于文本(或字符串)。 As far as I understand I have everything that is required, but obviously there's something missing.
据我了解,我拥有所有必需的东西,但显然缺少一些东西。
Any idea? 任何的想法?
If you make excel application visible xlsobj_2.Application.Visible = True
, you can see what really happened: when you execute this line chart.Copy
, it just copies chart sheet into new workbook. 如果使excel应用程序可见
xlsobj_2.Application.Visible = True
,则可以看到实际发生的情况:执行此折线图chart.Copy
,它只会将图表工作表复制到新工作簿中。 To fix it, use chart.ChartArea.Copy
instead: 要解决此问题,请改用
chart.ChartArea.Copy
:
Sub copy_pic_excel()
Dim xlsobj_2 As Object
Dim xlsfile_chart As Object
Dim chart As Object
Set xlsobj_2 = CreateObject("Excel.Application")
xlsobj_2.Application.Visible = False
Set xlsfile_chart = xlsobj_2.Application.Workbooks.Open("path_to_file.xlsx")
Set chart = xlsfile_chart.Charts("sigma_X_chart")
chart.Select
chart.ChartArea.Copy
With Selection
.PasteSpecial Link:=False, DataType:=wdPasteEnhancedMetafile, _
Placement:=wdInLine, DisplayAsIcon:=False
End With
'clean up
Set xlsfile_chart = Nothing
xlsobj_2.Quit
Set xlsobj_2 = Nothing
End Sub
also note that I've added clean up part of code to exit from excel application and clean memory. 还请注意,我添加了清理代码的一部分以退出excel应用程序并清理内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.