98.7% Of all customers recommend us, we're so confident about our results we publish all reviews and stats
View Live Stats View ReviewsForum home » Delegate support and help forum » Microsoft Excel VBA Training and help » Merge multiple sheets from multiple workbooks into one new sheet
Merge multiple sheets from multiple workbooks into one new sheet
Resolved · Medium Priority · Version 2016
Tom has attended:
Excel VBA Introduction course
Excel VBA Advanced course
Merge multiple sheets from multiple workbooks into one new sheet
Hi Jens
I'm just starting to get back to using VBA and a little bit rusty so appreciate any help you may be able to give around this...
I have multiple workbooks with multiple worksheets (the number of worksheets is not consistent across the workbooks and will vary over time) and I would like to merge them all into one worksheet in a new workbook. All the worksheets on every single workbook contain the exact same column headings which I would also like to include in the new worksheet.
I have used some of you code from previous forum questions mixed with my own but can't seem to get it to work - I think the issue is around line 39 - 42 where it currently picks just sheet 1 rather than all the sheets in the workbook so my loop just duplicates sheet 1 several times...
I also can't work out how to include the column headings (they are the same on every worksheet)...
Any help appreciated, even if you use completely different code!
Sub MergeAllWorkbooks()
Dim FolderPath As String 'store the folderpath in the computer's memory
Dim FileName As String 'store the file name inthe computer's memory
Dim WorkBk As Workbook 'store the name of each workbook in the computer's memory
Dim blankrow As Integer 'store the row number of the first blank row in destination sheet
Dim varAllData As Variant 'array. Will store all records from the source workbooks
Dim Current As Worksheet ' Declare Current as a worksheet object variable.
'speed up macro
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'open the select directory dialog box
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = -1 Then '-1 = yes or true
FolderPath = .SelectedItems(1) & "\"
Else
MsgBox "FilePath not selected!", , "Path selecter"
Exit Sub
End If
End With
'Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(FolderPath & "*.xl*")
'Loop until Dir returns an empty string
Do While FileName <> ""
'Open a workbook in the folder
Set WorkBk = Workbooks.Open(FolderPath & FileName)
For Each Current In Worksheets ' Loop through all of the worksheets in the active workbook
'This is where I begin to get muddled...
varAllData = WorkBk.Sheets(1).Range("a1").CurrentRegion.Offset(1, 0) 'selects sheet 1 from all workbooks and all data excluding the header
ThisWorkbook.Sheets("Sheet3").Activate 'name the location where you want the data to go
blankrow = Range("a1").CurrentRegion.Rows.Count + 1 'starting cell for data to be addedd to
Range("A" & blankrow).Resize(UBound(varAllData, 1), UBound(varAllData, 2)) = varAllData 'what you want to insert into that space
Next
'Need a clause to close the loop
'Close the source workbook without saving changes
WorkBk.Close savechanges:=False
'Use Dir to get the next file name
FileName = Dir()
Loop
Columns.AutoFit
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
RE: Merge multiple sheets from multiple workbooks into one new s
Hi Tom,
Thank you for your forum question. My name is Ron and I am one of the trainers at STL-training.
I had a look at your sample code. It all looks very impressive and I can see that you know what you are doing.
I suggest:
In VBeditor go to tools --> References and add the Microsoft Scripting Runtime library to your list of references.
This makes it much easier to obtain the file names in the folder and loop through them. It also has methods for creating files, seeing if files exist and other folder and file related methods
Below you will see some code that if you run it you will see it accesses every file in turn and returns the names of the sheets in each file. All you have to do is fill out the specific actions to implement to each sheet. Having had a look at your code I don't see you having any problem fitting that in.
Before you run the code please go to VB Editor --> view --> Immediate window. because the Debug.print line will print the file names and sheet names in the immediate window.
I have not catered for:
1. Using an IF construct to return nothing if the folder is empty
2. What needs to be done on each sheet you wish to merge.
Here is the code for the basic needs to loop through the files and sheets:
Dim fso 'variable to store the filesystem object
Dim objFolder
Dim objFile
dim ColFiles
Dim ws As Worksheet
Set fso = CreateObject("Scripting.FileSystemObject")
objFolder = "the file path to the folder goes here"
Set objFolder = fso.GetFolder(objFolder)
Set colFiles = objFolder.Files
'For eaxample:
For Each objFile In colFiles
Debug.Print objFile.Name
Workbooks.Open (objFile)
'This is where you insert the loop to go through each sheet in that particular workbook
For Each ws In objFile.Worksheets
'the code to indicate what you want to do with the sheets' data
Next
'for example:
For Each ws In ActiveWorkbook.Worksheets
Debug.Print ws.Name
Next
ActiveWorkbook.Close Savechanges = False
Next
NB. When copying and pasting this code and it does not work, please replace all the single and double quotes in the code because sometimes these are in a font style that the VB editor does not like. All you do is manually replace them.
I hope this helps you finish off your VBA project.
I do want to make you aware that the sort of process you are trying to program in VBA would be a doddle in Power Bi Desktop.
If you need anything else or the answer is not what you were looking for then please reply to this post.
Kind regards,
Ron Oldeboom
Learning and Development Consultant
STL-training
RE: Merge multiple sheets from multiple workbooks into one new s
Sorry Tom,
You need to obviously change the filepath in my code to the filepath in your environment where it says
objFolder = "the file path to the folder goes here"
Ron
Thu 16 Jul 2020: Automatically marked as resolved.
Training information:
Welcome. Please choose your application (eg. Excel) and then post your question. Our Microsoft Qualified trainers will then respond within 24 hours (working days). Frequently Asked Questions
Any suggestions, questions or comments? Please post in the Improve the forum thread. |
Excel tip:Repeating headings on spreadsheets that print on more than one pageBy default when you print a spreadsheet out and it prints on more than one page, the headings at the top and the side of the spreadsheet don't appear on all the pages following page 1. |