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 » Combining data from multiple workbooks
Combining data from multiple workbooks
Resolved · Low Priority · Version 2010
Steve has attended:
Excel VBA Introduction course
Excel VBA Intermediate course
Combining data from multiple workbooks
I discussed this briefly with Jens after the beginner VBA course yesterday:
I have several workbooks within a folder (they are the only workbooks within this folder) that all have an identical format and contain one worksheet each. I need to create a new workbook which just accumulates all of the entries from the various workbooks into one big worksheet. Note that the number of workbooks in the folder can vary, and also the number of entries in each worksheet can vary, so both of these will need to be dynamic. It should also be noted that each of the worksheets contain the same headers, which will obviously only need to be copied over once into the new workbook (i.e. row 1 contains the headers and rows 2 onwards contain the entries)
My thoughts are that I will need a dynamic "for each" loop to circulate through the workbooks in the folder, but I am unsure how to define the folder etc. I would then assume that I can create some code to select all rows, copy and paste into the new workbook.
I hope the above information is clear, and would appreciate any help that can be offered.
Regards,
Steve Wilson
RE: Combining data from multiple workbooks
Hi Steve,
Thank you for the forum question and the nice feedback yesterday.
The code below will do what you need. You may need to amend it. The code is copy and pasting all records for any number of workbooks stored in a folder, but the only from sheet 1 in the source workbooks. The lists in sheet 1 all starts from row 1.
You can change the line below, if you do not have the data in sheet1 and change Range("a1") if your list do not starts from A!:
varAllData=WorkBk.Sheets(1).Range("a1").CurrentRegion.Offset(1, 0)
You will need to change the line below as well. Change "Destination" to the name of your destination sheet.
ThisWorkbook.Sheets("Destination").Activate
Copy the code below and paste it in the destination workbook.
Option Explicit
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
Application.ScreenUpdating = False
Application.DisplayAlerts = False
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
FileName = Dir(FolderPath & "*.xl*")
Do While FileName <> ""
Set WorkBk = Workbooks.Open(FolderPath & FileName)
varAllData = WorkBk.Sheets(1).Range("a1").CurrentRegion.Offset(1, 0)
ThisWorkbook.Sheets("Destination").Activate
blankrow = Range("a1").CurrentRegion.Rows.Count + 1
Range("A" & blankrow).Resize(UBound(varAllData, 1), UBound(varAllData, 2)) = varAllData
WorkBk.Close savechanges:=False
FileName = Dir()
Loop
Columns.AutoFit
Application.ScreenUpdating = True
Application.DisplayAlerts = True
end Sub
Kind regards
Jens Bonde
Microsoft Office Specialist Trainer
Tel: 0207 987 3777
Best STL - https://www.stl-training.co.uk
98%+ recommend us
London's leader with UK wide delivery in Microsoft Office training and management training to global brands, FTSE 100, SME's and the public sector
RE: Combining data from multiple workbooks
Hi Jens,
Many thanks for the above - it works absolutely perfectly for my purposes!
I have been asked by a colleague whether the above code would also work for workbooks that are stored on a SharePoint folder, however this generates the following error:
Run-time error '52':
Bad file name or number
As mentioned, the above code works perfectly for my purposes, so offering a possible solution to the SharePoint question is not a priority, but if you are able to offer assistance that would be much appreciated.
Many thanks again for your course yesterday - I found it very informative and am looking forward to the intermediate course in a couple of weeks time!
Steve
RE: Combining data from multiple workbooks
Hi Steve,
The code below can be use for SharePoint folders. I have not been able to test it, but it should be fine. Please let me know if it is not working.
Sub ListAllFile()
Dim objFSO As Object
Dim objFolder As Object
Dim ObjFile As Object
Dim pth As String
Dim WBn As Workbook
Dim ObCount As Long
Dim FileNme As String
Dim varAllData as variant
Application.ScreenUpdating = False
Set objFSO = CreateObject("Scripting.FileSystemObject")
‘Get the folder object associated with the directory
Set objFolder = objFSO.GetFolder("//projectspace/ColleagueResponses/")
‘You'll need to specify your path here. By removing the http: from the path, the code liked it & found the folder. It wasn’t working previously ***
pth = http://projectspace/colleagueResponses/
‘You'll need to specify your path here. The reason I’ve done this separately is because the path is not recognised otherwise when trying to specify it with workbook.open & using the value set for objFolder
ObCount = objFolder.Files.Count
‘ counts the number of files in the folder
‘Loop through the Files collection
For Each ObjFile In objFolder.Files
Nm1 = Len("\\projectspace\colleagueResponses\")
‘You'll need to specify your path here
Nm2 = Len(ObjFile) - Nm1
FileNme = Right(ObjFile, Nm2)
‘I’ve done this part to find out/set the file name**
Set WBn = Workbooks.Open(pth & FileNme, , , , Password:="Password1")
‘opens the first file in the library – if there is no password, the remove everything from - , , , , Password:="Password1" – leaving the close bracket ‘)’
varAllData =WBn.Sheets(1).Range("a1").CurrentRegion.Offset(1, 0)
ThisWorkbook.Sheets("Destination").Activate
blankrow = Range("a1").CurrentRegion.Rows.Count + 1
Range("A" & blankrow).Resize(UBound(varAllData, 1), UBound(varAllData, 2)) = varAllData
WBn.Close savechanges:=False
Next
‘goes to next file within your sharepoint folder
Application.ScreenUpdating = True
End Sub
Kind regards
Jens Bonde
Microsoft Office Specialist Trainer
Tel: 0207 987 3777
Best STL - https://www.stl-training.co.uk
98%+ recommend us
London's leader with UK wide delivery in Microsoft Office training and management training to global brands, FTSE 100, SME's and the public sector
Wed 16 Aug 2017: 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:Return to the active cell after scrollingWhen I scroll a long way down the screen from a selected cell, I can return to that cell with the Ctrl+Back Space shortcut. The active cell now appears in roughly the middle of the screen. |