snaut
snaut

Reputation: 2535

Combine Word Documents using script

I was wondering if I could automate a task I'm doing manually now. I have folders, each with two word documents. I combine both documents with Combine from the Review ribbon and save the document for someone else to review the changes.

Can I automate creating those files, for example with powershell or VBA?

Upvotes: 1

Views: 2289

Answers (1)

Theo
Theo

Reputation: 61068

To combine two word documents using PowerShell, you can use this:

$document1      = 'D:\Test\firstDoc.docx'
$document2      = 'D:\Test\secondDoc.docx'
$resultDocument = 'D:\Test\combined.docx'  # the output file

$word = New-Object -ComObject Word.Application
$word.Visible = $false

$doc   = $word.Documents.Open($document1)
$range = $doc.Range()
# move to the end of the first document
$range.Collapse(0)     # wdCollapseEnd see https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.wdcollapsedirection
# insert a page break so the second document starts on a new page
$range.InsertBreak(7)  # wdPageBreak   see https://learn.microsoft.com/en-us/office/vba/api/word.wdbreaktype
$range.InsertFile($document2)

$doc.SaveAs($resultDocument)
# quit Word and cleanup the used COM objects
$word.Quit()

$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($range)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

P.S. You need to use full, absolute file paths when using COM objects

Upvotes: 3

Related Questions