【发布时间】:2020-09-15 14:03:10
【问题描述】:
我正在尝试在 Excel 中编写 VBA 代码来更新 Word 报告。
我正在从 Stack Overflow 复制代码片段并对其进行调整。
我所有的代码都在工作,我单独尝试过,但是这一行:
ActiveDocument.Selection.PasteSpecial
它给出以下错误代码:
运行时错误 438:对象不支持此属性或方法。
完整代码:
Sub UpdateReport()
'
' UpdateReport Macro
' Update the monthly ITCV report
'
'
Dim wd As Object
Dim ObjDoc As Object
Dim FilePath As String
Dim FileName As String
Dim originalImage As InlineShape
Dim Lines(1 To 8) As Long
Lines(1) = 103
Lines(2) = 107
Lines(3) = 109
Lines(4) = 110
Lines(5) = 115
Lines(6) = 116
Lines(7) = 117
Lines(8) = 121
FilePath = "C:\Users\nmoesen\Desktop"
FileName = "Test.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
'initialise loop
For i = LBound(Lines) To UBound(Lines)
'set value to generate correct chart
Sheets("Calculations").Range("AE2").Value = Lines(i)
'copy chart from Excel
Sheets("Calculations").ChartObjects("Chart 1").Chart.ChartArea.Copy
Set originalImage = ActiveDocument.InlineShapes(i)
Dim imageControl As ContentControl
If originalImage.Range.ParentContentControl Is Nothing Then
Set imageControl = ActiveDocument.ContentControls.Add(wdContentControlPicture, originalImage.Range)
Else
Set imageControl = originalImage.Range.ParentContentControl
End If
Dim imageW As Long
Dim imageH As Long
imageW = originalImage.Width
imageH = originalImage.Height
originalImage.Delete
ActiveDocument.Bookmarks("Bookmark" & i).Select
ActiveDocument.Selection.PasteSpecial Link:=False, _
DataType:=wdPasteMetafilePicture, _
Placement:=wdInLine, _
DisplayAsIcon:=False
With imageControl.Range.InlineShapes(i)
.Height = imageH
.Width = imageW
End With
Next i
End Sub
【问题讨论】:
-
当您已经将
ObjDoc定义为您需要使用的文档时,为什么还要使用ActiveDocument? -
我会尝试使用它,看看它是否有帮助!编辑:刚刚尝试将其更改为 ObjDoc,得到了同样的错误。