从一个 Word 文档复制到另一个文档导致 运行 次错误 4605

Copying from One Word Document to Another Results in Run-time error 4605

我正在尝试从一个 word 文档中复制文本以替换另一个文档中的特定段落。代码如下:

Sub OpenDoc()
    Dim strFile1 As String
    Dim strFile2 As String
    Dim oDoc1 As Document
    Dim oDoc2 As Document
       
    strFile1 = "C:\Users\Name\Documents\Example Doc1.docm"  
    
    If Dir(strFile1) <> "" Then        
        Set oDoc1 = Documents.Open(strFile1)
        oDoc1.Paragraphs(1).Range.Copy
  
    End If

    strFile2 = "C:\Users\Name\Documents\Example Doc2.docm"    
    If Dir(strFile2) <> "" Then       
        Set oDoc2 = Documents.Open(strFile2)
        oDoc2.Paragraphs(7).Range.PasteAndFormat(wdPasteDefault)
       
    End If
End Sub

虽然两个文档都打开,但解决方案间歇性地工作:首先 运行 它有效,但是 运行 再次可能会给出 运行-time 错误 4605 此命令不可用,并选择 oDoc2.Paragraphs(7).Range.PasteAndFormat(wdPasteDefault) 作为有问题的行。如果我在错误后重新设置代码,它可能 运行 完美。我不明白为什么它有时有效,而其他时候无效。

如果我尝试手动粘贴,出现错误后,结果正是应该复制的内容。所以我认为我从第一个文档中复制的方式没有任何问题。

看起来如果我关闭正在粘贴文本的文档然后 运行 代码,它每次都能正常工作。但是,如果我每次都必须等待文档打开,这个过程会变得很慢。

您可以在不使用复制和粘贴的情况下执行此操作。

Sub OpenDoc()
    Dim strFile1 As String
    Dim strFile2 As String
    Dim oDoc1 As Document
    Dim oDoc2 As Document
       
    strFile1 = "C:\Users\Name\Documents\Example Doc1.docm"
    
    If Dir(strFile1) <> "" Then Set oDoc1 = Documents.Open(strFile1)
  
    strFile2 = "C:\Users\Name\Documents\Example Doc2.docm"
    If Dir(strFile2) <> "" Then Set oDoc2 = Documents.Open(strFile2)
    
    If Not oDoc1 Is Nothing Then
        If Not oDoc2 Is Nothing Then
            oDoc2.Paragraphs(7).Range.FormattedText = oDoc1.Paragraphs(1).Range.FormattedText
        End If
    End If
End Sub