我是VBA的新手,但我已经设法凑齐了一些代码,这些代码允许我将excel 2010图表导出到新的Word 2010文档中。我唯一的问题是,我想在导出图表时将图表与excel取消链接,以便在更新excel时不会更改图表。我到处寻找,但似乎没有任何效果。
唯一适合该法案的其他代码采用图表并在粘贴之前将其保存为图像,但这不起作用,因为我无处保存图像 - 我们组织中的用户无法访问C:\驱动器,在不知道每个人的用户详细信息的情况下,我无法编写可以完成工作的代码。
我到目前为止编写的代码是这样的,它确实有效,但没有取消链接:
Sub Copy_Paste_Report_1_Graph_to_new_word_document()
'
'Copy/Paste An Excel Chart Into a New Word Document
'(VBE > Tools > References > Microsoft Word 12.0 Object Library)
'Excel Objects
Dim ChartObj As ChartObject
'Word Objects
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
'Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False
'Copy Chart from Excel
Set ChartObj = Worksheets("External Dashboard").ChartObjects("Chart 1")
'Create an Instance of MS Word
On Error Resume Next
'Is MS Word already opened?
Set WordApp = GetObject(class:="Word.Application")
'Clear the error between errors
Err.Clear
'If MS Word is not already open then open MS Word
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
'Handle if the Word Application is not found
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
GoTo EndRoutine
End If
On Error GoTo 0
'Make MS Word Visible and Active
WordApp.Visible = True
WordApp.Activate
'Create a New Document
Set myDoc = WordApp.Documents.Add
'Copy Excel Chart
ChartObj.Copy
'Paste Chart into MS Word
myDoc.Paragraphs(1).Range.PasteSpecial Link:=False _
EndRoutine:
'Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
End Sub
我可能包含的内容超出了我的需要,但就像我说的那样,我是新手。
答案 0 :(得分:0)
使用.CopyPicture
和.PasteSpecial
方法:
Sub Copy_Paste_Report_1_Graph_to_new_word_document()
Dim ChartObj As ChartObject
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Set ChartObj = Worksheets("External Dashboard").ChartObjects("Chart 1")
Set WordApp = CreateObject(class:="Word.Application")
WordApp.Visible = True
WordApp.Activate
Set myDoc = WordApp.Documents.Add
ChartObj.CopyPicture xlScreen, xlPicture
myDoc.Paragraphs(1).Range.PasteSpecial
End Sub