I'm trying to copy the text from one word document to replace a specific paragraph in another. The code is below:
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
While both documents are open, the solutions work intermittently: First run it works, but running again might give Run-time error 4605 This command is not available, and selects oDoc2.Paragraphs(7).Range.PasteAndFormat(wdPasteDefault)
as the problematic line. If I reset the code after the error, it might run perfectly. I cannot figure out why it works sometimes and not others.
If I try pasting manually, after getting the error, the result is exactly what should have been copied. So I don't think there is anything wrong with how I copied from the first document.
It also looks like if I close the document which the text is being pasted and then run the code, it works every time. However, the process become a lot slower if I have to wait for the document to open each time.
CodePudding user response:
You can do this without using copy and paste.
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