在Excel中,我需要复制/粘贴到Word文档中约20张,每张都有20张图表。每个Excel工作表一个Word文档。我发现this article的解决方案经过修改,可以接受ChartObject作为参数,因此不必考虑要复制哪个图表。我在CopyChart2Word()函数中调用PasteSpecial的最后一行收到以下运行时错误:
这不是很有帮助,因为它不会告诉我什么地方出了问题。但是,该图表粘贴到Word文档中,但缺少了一半的数据点。
代码:
Public Function moveCharts()
Dim i As Integer
Dim name As String
Dim ChtObj As ChartObject
Dim dummy As Variant
initGlobals
For i = 0 To UBound(employees)
name = employees(i)
For Each ChtObj In Worksheets(name).ChartObjects
dummy = CopyChart2Word(ChtObj)
Next ChtObj
Next i
End Function
Public Function CopyChart2Word(chartObj As ChartObject)
Dim wd As Object
Dim ObjDoc As Object
Dim FilePath As String
Dim FileName As String
FilePath = "C:\Users\name\Desktop"
'Empty document for now
FileName = "Template.docx"
'check if template document is open in Word, otherwise open it
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
Set wd = CreateObject("Word.Application")
Set ObjDoc = wd.Documents.Open(FilePath & "\" & FileName)
Else
On Error GoTo notOpen
Set ObjDoc = wd.Documents(FileName)
GoTo OpenAlready
notOpen:
Set ObjDoc = wd.Documents.Open(FilePath & "\" & FileName)
End If
OpenAlready:
On Error GoTo 0
'find Bookmark in template doc
wd.Visible = True
'ObjDoc.Bookmarks("Bookmark1").Select
'copy chart from Excel
chartObj.chart.ChartArea.Copy
'insert chart to Bookmark in template doc
'wdPasteMetafilePicture didn't work so I used the numeric value 3
'wdInLine didn't work so I used the numeric value 0
wd.Selection.PasteSpecial Link:=False, _
DataType:=3, _
Placement:=0, _
DisplayAsIcon:=False
End Function
链接到sample chart。
我怀疑该错误可能是由于同时打开Word的不同实例引起的。为了消除这种可能性,我建议理清处理Word和文档的方式。您的代码逻辑有些混乱。请改用此方法。
On Error Resume Next
Set Wd = GetObject(, "Word.Application")
If Err Then Set Wd = CreateObject("Word.Application")
On Error Resume Next
Set ObjDoc = Wd.Documents(Filename)
If Err Then Set ObjDoc = Wd.Documents.Open(FilePath & "\" & Filename)
On Error GoTo 0
我想知道为什么您需要Wd.Visible = True
。默认情况下它应该是可见的。但是,窗口可能不是ActiveWindow。实际上,Word可能不是活动的应用程序。我认为代码无关紧要。
但是对Selection
对象应该有很大的影响。仅ActiveWindow可以具有Selection
。因此,如果打开Excel并运行代码,则无法访问Word中的Selection
对象。相反,如果打开Word并进行选择,然后更改为Excel,则Selection
对象将丢失。这也可能导致致命错误。只需遵循以下规则:“在VBA中从不Select
任何内容[直到代码的最后一行]。