PDA

View Full Version : Word365 Doc.Activate and Paste range from other document



tonse
08-04-2021, 12:23 AM
Hi

I recently changed to 365. Ik have a macro that opens a second document and copies blocks of information to the orginal document. The user can select with informtion he wants to paste
I get a 4605 error message now.

My code is

Documents(OriDoc).Activate
Selection.Move Unit:=wdCell, Count:=1
Set SrcRng = Documents(OpenFile).Sections(4).Range
SrcRng.Select
SrcRng.MoveEnd wdCharacter, -1 'Alles selecteren behalve Sectie-einde
SrcRng.Copy
Documents(OriDoc).Activate
Selection.Paste


Before this code a table is inserted from a building block. The original document is activated and the cursor is moved to the correct cell. Then the source doc is opened, and a section is copied.
The Oridoc is activated again and the contents is pasted
The error message occurs on "Selection.Paste"

The strange behavior is that when i press error detection (i do not know the correct translatation form this out of Dutch, but it is the most right button in the errordialog) en then press CTRL-SHIFT-F8 to step over , then contents is nicely pasted as i want it....

Before 365 this error did not occur....

tonse
08-04-2021, 02:24 AM
I checked some more behaviour...
I have some old "source documents" that show in compatibility mode when normally openen form explorer
These documents do not give that problem
Only newly (in 365) created documents create that problem....

gmayor
08-06-2021, 11:28 PM
The code does not make clear what the documents referred to are, however, try the following


Sub Macro1()
Const strSrc As String = "C:\Path\OpenFile.docx" 'the path of the document that is OpenFile
Dim OriDoc As Document
Dim OpenFile As Document
Dim SrcRng As Range, TgtRng As Range

'The document must already be active in order to set a selection range
Set OriDoc = ActiveDocument

If Selection.Information(wdWithInTable) = False Then
MsgBox "The cursor is not in a table cell?", vbCritical
GoTo lbl_Exit
End If

'not sure what the next line is for. Put the cursor in the cell where you want the inserted data
'Selection.Move Unit:=wdCell, Count:=1

Set TgtRng = Selection.Cells(1).Range
TgtRng.End = TgtRng.End - 1

Set OpenFile = Documents.Open(strSrc)
If OpenFile.Sections.Count < 4 Then
MsgBox "The source document doesn't have 4 sections", vbCritical
GoTo lbl_Exit
End If
Set SrcRng = OpenFile.Sections(4).Range
SrcRng.End = SrcRng.End - 1
TgtRng.FormattedText = SrcRng.FormattedText 'simply write the data to the cell
lbl_Exit:
Documents(OriDoc).Activate
Set OriDoc = Nothing
Set OpenFile = Nothing
Set SrcRng = Nothing
Set TgtRng = Nothing
Exit Sub
End Sub