Consulting

Results 1 to 3 of 3

Thread: Merging word documents from Excel using Word templates

  1. #1
    VBAX Newbie
    Joined
    Nov 2014
    Posts
    2
    Location

    Merging word documents from Excel using Word templates

    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

    HTML Code:
    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

  2. #2
    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
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

  3. #3
    VBAX Newbie
    Joined
    Nov 2014
    Posts
    2
    Location
    Problem solved thanks. I wasn't aware of the FormattedText property, which looks very useful I have to say as it's Read/Write.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •