Word 2010 Macro to Merge Files Not Working

Alex Campbell
Alex Campbell used Ask the Experts™
on
This macro is to merge all the files in a folder into the current document BUT I would also like to be able to tell it a different folder OR even better to tell it to merge only selected files in a folder.  Number one goal is to get the merge working.

Sub MergeDocs()
Dim rng As Range
Dim MainDoc As Document
Dim strFile As String
Const strFolder = "U:\MergeDocs\"
Set MainDoc = Documents.Add
strFile = Dir$(strFolder&"*.docx")
Do Until strFile = ""
Set rng = MainDoc.Range
rng.Collapse wdCollapseEnd
rng.InsertFile strFolder & strFile
strFile = Dir$()
Loop
End Sub

Open in new window

Word-Macro-Merge-File.jpg
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Retired
Top Expert 2012
Commented:
The & in the strFile= line needs to be surrounded by spaces.

To change the folder, you need to type in a different value for the strFolder constant.

Sub MergeDocs()
    Dim rng As Range
    Dim MainDoc As Document
    Dim strFile As String
    
    Const strFolder = "W:\Another Folder\"
    
    Set MainDoc = Documents.Add
    strFile = Dir$(strFolder & "*.docx")
    Do Until strFile = ""
        Set rng = MainDoc.Range
        rng.Collapse wdCollapseEnd
        rng.InsertFile strFolder & strFile
        strFile = Dir$()
    Loop
End Sub

Open in new window

GrahamSkanRetired
Top Expert 2012
Commented:
If you don't want to work with a single folder, you could present your files in an array:

Sub CallMergeMyDocList()
    Dim MyFiles() As String
    
    ReDim MyFiles(2)
    MyFiles(0) = "C:\Folder1\Doca.doc"
    MyFiles(1) = "w:\Folderb\Doc1.doc"
    MyFiles(2) = "x:\myfolder\Doc4.doc"
    MergeMyDocList MyFiles()
End Sub

Sub MergeMyDocList(strFiles() As String)
    Dim rng As Range
    Dim MainDoc As Document
    Dim f As Integer
    
    For f = 0 To UBound(strFiles)
        Set MainDoc = Documents.Add
        Set rng = MainDoc.Range
        rng.Collapse wdCollapseEnd
        rng.InsertFile strFiles(f)
    Next f
End Sub

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial