Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge excel workbooks from folder into new open workbook

This Macro I have continues to merge the files from my folder into the current open workbook. I am trying to open a new workbook and have it merge into the new open workbook. I am not sure where I need to activate the newly opened/ added workbook in order for the merge to take place in that file.

Sub MergeWorkbooks()


Application.DisplayAlerts = False
Workbooks.Add
ActiveWorkbook.SaveAs FileName:="C:\ ....\Merged Files.xlsx"

Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Application.ScreenUpdating = False
FolderPath = "<Folder destination>"
Filename = Dir(FolderPath & "*.xls*")
 
workbooks("Merged Files.xlsx").Activate

Do While Filename <> ""
 Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
 For Each Sheet In ActiveWorkbook.Sheets
 Sheet.Copy After:=ThisWorkbook.Sheets(1)
 Next Sheet
 Workbooks(Filename).Close
 Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Since Workbooks.Add and Workbooks.Open return a reference to the newly added or opened workbook, use two Workbook variables:

Dim mergedWb As Workbook
Set mergedWb = Workbooks.Add()

mergedWb.SaveAs FileName:="C:\ ....\Merged Files.xlsx"

...

Do While Filename <> ""
    Dim wb As Workbook
    Set wb = Workbooks.Open(Filename:=FolderPath & Filename, ReadOnly:=True)
 
    For Each Sheet In wb.Sheets
       Sheet.Copy After:=mergedWb.Sheets(1)
    Next Sheet
 
    wb.Close
    Filename = Dir()
Loop
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading