agent_maxine
New Member
- Joined
- Aug 23, 2017
- Messages
- 38
Dear Mr. Excel,
Would like to request your kind assistance on my codes below... I have codes that will allow me to select multiple files and combine them into 1 Word (then exports into 1 PDF). Problem is:
How can I make it so that the Combined File keeps the formatting of individual documents? Codes were adopted from this page:
https://www.datanumen.com/blogs/2-ways-quickly-merge-multiple-word-documents-one-via-vba/
Would like to request your kind assistance on my codes below... I have codes that will allow me to select multiple files and combine them into 1 Word (then exports into 1 PDF). Problem is:
- Headers/Footers: The header/footer from the first file is used for the entire combined file.
- Font Types/Sizes/Layouts: It seems to use the Word default template's font type/sizes and disregards the types used in original Word documents (even the first file).
How can I make it so that the Combined File keeps the formatting of individual documents? Codes were adopted from this page:
https://www.datanumen.com/blogs/2-ways-quickly-merge-multiple-word-documents-one-via-vba/
Code:
Sub Combine_Selected_Documents()
Dim dlgFile As FileDialog
Dim nTotalFiles As Integer, nEachSelectedFile As Integer
Dim strFolder As String, myFolder As folder
Dim fso As FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
Set dlgFile = Application.FileDialog(msoFileDialogFilePicker)
With dlgFile
.AllowMultiSelect = True
If .Show <> -1 Then
Exit Sub
Else
strFolder = .SelectedItems(1) & Application.PathSeparator
nTotalFiles = .SelectedItems.Count
End If
End With
'Add code to check if PDF file exists, if no Word files were selected, if it works with different Word Document names, etc.
Dim myArr
myArr = Split(strFolder, "\")
strFolder = myArr(0)
For i = 1 To UBound(myArr) - 2
strFolder = strFolder & "\" & myArr(i)
Next i
strFolder = strFolder & "\"
'MsgBox strFolder
Dim objWord As Word.Application
Set objWord = CreateObject("Word.Application")
Dim objDoc As Word.Document
Set objDoc = objWord.Documents.Add
objWord.Visible = False 'Temporary
Set objSelection = objWord.Selection
'objSelection.TypeText ("This is my text in Word Document using Excel")
For nEachSelectedFile = 1 To nTotalFiles
objSelection.InsertFile dlgFile.SelectedItems.Item(nEachSelectedFile)
If nEachSelectedFile < nTotalFiles Then
objSelection.InsertBreak Type:=wdSectionBreakNextPage
Else
If nEachSelectedFile = nTotalFiles Then
objDoc.ExportAsFixedFormat OutputFileName:=strFolder & "Forms.pdf", ExportFormat:=wdExportFormatPDF ', OpenafterPublish:=OpenafterPublish
objDoc.SaveAs2 (strFolder & "Forms Combined.docx")
objDoc.Close
'objWord.Quit
Exit Sub
End If
End If
Next nEachSelectedFile
MsgBox "All the Selected Documents have been Combined into 1 PDF File."
End Sub