0
votes

I am trying to copy entire content (including page numbers, and page layout) from a word document to another, using Microsoft.Office.Interop.Word. I cannot use SaveAs method because the document in which I want to paste the contents is already created and it contains VBA code. Also, I cannot use XML related code because the document in which I am copying the content is in the older format. This document is part of an old way of uploading a document to a server database, using VBA code.

Using VBA code, I can copy the entire content without any issue.

 Selection.WholeStory
 Selection.Copy
 Windows("document.doc").Activate
 Selection.WholeStory
 Selection.PasteAndFormat (wdFormatOriginalFormatting)

For C#, I used Microsoft.Office.Interop.Word to replicate the VBA code.

Word.Application objWordOpen = new Word.Application();
objWordOpen.Visible = false;
Word.Document doclocal = objWordOpen.Documents.Open(filepath);

doclocal.ActiveWindow.Selection.WholeStory();
doclocal.ActiveWindow.Selection.Copy();

Document d1 = objWordOpen.Documents.Open(filepath2);
d1.Activate();
d1.ActiveWindow.Selection.WholeStory();
d1.ActiveWindow.Selection.PasteAndFormat(Word.WdRecoveryType.wdFormatOriginalFormatting);

I have also tried using range

Word.Range oRange = doclocal.Content;
oRange.Copy();

The content is copied into the document, but without headers and footers. Also, when using Selection.WholeStory() approach, the page margins settings don't get copied. What changes should I make to the c# code in order to achieve my result?

1
Try opening both files first and then copying. - GSerg
Can you just copy the whole actual file instead? - Tony
@GSerg, it works opening both files before, but I don't understand what's the relevance. You could post an answer, explaining why, if you came across this issue. Thank you! - Cosmin
The act of opening a document messes up with Selection. It's an observation, I do not have concrete documentation. - GSerg
@GSerg, I can see why it would mess up with the Selection. However, my initial code opened the document after copying the selection, so the initial selection shouldn't matter anymore. Anyhow, please post your comment an anwser so I can mark the Question as anwered. Thank you again! - Cosmin

1 Answers

1
votes

MS Office applications have complicated relationships with the clipboard. Between various optimisations that may lead to cryptic prompts, and numerous formats they support, it is best to not do anything remotely funny between a Copy and a Paste.

The VBA code follows this advice, the C# code opens a document between copying and pasting.

Make sure you open the documents in advance and not in the middle of a copypaste.