PDA

View Full Version : [SOLVED:] Merging word documents from Excel using Word templates



wullie
11-10-2014, 09:40 AM
Hi,

As per snb's post in thread '37720-Merging-two-Word-documents-into-one-from-Excel', I have managed to get documents to combine, but the merging only copies the textual content of the files that I want to merge and not the tables in the templates.

Is there a way to do this that I am missing?

My code currently for the section I need is


Set wrdDoc = wrdApp.Documents.Open(objFolder & "\" & specialties(specialtyLoop) & "Combined.doc")
wrdApp.Visible = True
With wrdDoc
.Content.InsertAfter GetObject(objFolder & "\" & files(fileLoop)).Content
.SaveAs2 objFolder & "\" & specialties(specialtyLoop) & "Combined.doc", 12
.Close False
End With

I have also tried replacing the InsertAfter with '.Content.InsertFile Filename:=objFolder & "\" & files(fileLoop)', but that seems to overwrite rather than appending to the content.

Further to this, I have tried copy and pasting, which does copy the template as well, but pastes in place of the existing text (or visibly on top of when using OLEObject) and I can't seem to get it to escape off of the selection and to the bottom of the document.

Any help would be greatly appreciated.

Thanks

gmayor
11-10-2014, 11:37 PM
The following should help. You can adapt it to your code as required. Note that documents are made up of multiple elements or story ranges, It gets complicated if you want to merge more than the document bodies, but documents with tables should be OK.


Set wrdTarget = wrdApp.Documents.Open("C:\Path\Document1.docx") 'The document that combines the content
Set wrdDoc = wrdApp.Documents.Open("C:\Path\Document2.docx") 'The document to be added
wrdTarget.Range.InsertParagraphAfter 'add a paragraph break at the end of the target document
Set oRng = wrdTarget.Range 'Set a range to the target document body
oRng.Collapse 0 'Collapse the range to the end
oRng.FormattedText = wrdDoc.Range.FormattedText 'Add the document body to the range

wullie
11-11-2014, 03:28 AM
Problem solved thanks. I wasn't aware of the FormattedText property, which looks very useful I have to say as it's Read/Write.