Originally Posted by
gonen
Could you pls add few lines to the code that will save the merged new file to a new file name (without actually touching the original file) ?
Sure, use this code:
Sub MergeDocs2()
'ZVI:2013-10-08 http://www.vbaexpress.com/forum/showthread.php?47741-Word-macro-need-to-run-it-from-excel
Const DestFile As String = "AllMerged.docx"
Const wdCollapseEnd As Long = 0, wdPageBreak As Long = 7, wdFormatDocument As Long = 0, wdFormatXMLDocument As Long = 12
Dim objWord As Object, strFile As String, strFile1 As String, strFolder As String, strDestFile As String
' If this workbook is saved in the same folder as the DOCs then use this line:
strFolder = ThisWorkbook.Path & "\"
' Else uncomment the line below and change it appropriately
'strFolder = "d:\aagon\data\Poi\Dropbox\Family\Miki\Envelope_to_send\"
' Get/Create Word Application object
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If Err <> 0 Then Set objWord = CreateObject("Word.Application")
' Trap errors
On Error GoTo exit_
' Kill previous result
strDestFile = DestFile
If Val(objWord.Version) < 12 Then strDestFile = Left(strDestFile, Len(strDestFile) - 1)
If Len(Dir(strFolder & strDestFile)) > 0 Then Kill strFolder & strDestFile
' Find name of the 1st document and save its name
strFile = Dir$(strFolder & "*.doc*")
strFile1 = strFile
' Merge documents
If Len(strFile) Then
With objWord.Documents.Open(strFolder & strFile, , True)
While Len(strFile)
If strFile <> strFile1 And strFile <> strDestFile Then
With .Range.Characters.Last
.Collapse wdCollapseEnd
.InsertBreak wdPageBreak
.InsertFile strFolder & strFile
End With
End If
strFile = Dir$
Wend
' Save the result
.SaveAs strFolder & strDestFile, FileFormat:=IIf(Val(objWord.Version) < 12, wdFormatDocument, wdFormatXMLDocument)
' Uncomment the next line to close the resulting document
'.Close False
End With
End If
exit_:
objWord.Visible = True
If Err Then MsgBox strFile & vbLf & Err.Description, vbCritical, "Error #" & Err.Number
' Release the memory
Set objWord = Nothing
End Sub