|
Combine Multiple Workbooks into One
This macro for Microsoft Excel allows you to combine multiple workbooks and worksheets into one new workbook and worksheet. When the macro runs, it prompts you to select which excel files from your computer you would like to combine and, once you select them and press ok, this macro will pull data from pre-specified worksheets in the selected workbooks and then combine the data onto one worksheet within a new excel workbook. This works quickly and easily and does not require the hard-coding of file names into the macro.
Note: This macro goes into a Module. Also, you will need to change some cell references and worksheet references if you want the macro to work for your specific needs.
Change the number in this line of code With mybook.Worksheets(1) to choose which worksheet you want data to be copied from in the workbook. 1 means the first sheet and 2 the second sheet etc.
Change the cell references in this line of code Set sourceRange = .Range("A1:A25") to the cells you want to be copied from the old worksheet onto the new worksheet.
Change the column reference in this line of code Set destrange = BaseWks.Range("A" & rnum) which is now "A" to whatever column you would like the cells to be imported.
Change this line of code to point to a specific directory where you want the macro to point by default ChDirNet "C:\".
Where to install the macro: Module
Excel Macro to Combine Multiple Workbooks into One
Private Declare Function SetCurrentDirectoryA Lib _
"kernel32" (ByVal lpPathName As String) As Long
Sub ChDirNet(szPath As String)
SetCurrentDirectoryA szPath
End Sub
Sub Combine_Workbooks_Select_Files()
Dim MyPath As String
Dim SourceRcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
Dim SaveDriveDir As String
Dim FName As Variant
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
SaveDriveDir = CurDir
ChDirNet "C:\"
FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
MultiSelect:=True)
If IsArray(FName) Then
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
For Fnum = LBound(FName) To UBound(FName)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(FName(Fnum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
With mybook.Worksheets(1)
Set sourceRange = .Range("A1:A25")
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Not enough rows in the sheet. "
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
Set destrange = BaseWks.Range("A" & rnum)
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next Fnum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
ChDirNet SaveDriveDir
End Sub
How to Install the Macro
- Select and copy the text from within the grey box above.
- Open the Microsoft Excel file in which you would like the Macro to function.
- Press "Alt + F11" - This will open the Visual Basic Editor - Works for all Excel Versions.
Or For other ways to get there, Click Here.
For Excel Versions Prior to Excel 2007 Go to Tools > Macros > Visual Basic Editor
For Excel 2007 Go to Office Button > Excel Options > Popular > Click Show Developer tab in the Ribbon. Then go to the Developer tab on the ribbon menu and on the far left Click Visual Basic
- On the new window that opens up, go to the left side where the vertical pane is located. Locate your Excel file; it will be called VBAProject (YOUR FILE'S NAME HERE) and click this.
- If the Macro goes in a Module, Click Here, otherwise continue to Step 8.
- Go to the menu at the top of the window and click Insert > Module
- Another window should have opened within the Visual Basic Editor's window. Within this new window, paste the macro code. Make sure to paste the code underneath the last line of anything else that is in the window.
- Go to Step 8.
- If the Macro goes in the Workbook or ThisWorkbook, Click Here, otherwise continue to Step 8.
- Directly underneath your excel file called VBAProject(your file's name here), click the Microsoft Excel Objects folder icon to open that drop-down list.
- Then, at the bottom of the list that appears, double-click the ThisWorkbook text.
- A new window inside the Visual Basic Editor's window will appear. In this new window, paste the code for the macro. Make sure to paste this code underneath the last line of any other code which is already in the window.
- Go to Step 8.
- If the Macro goes in the Worksheet Code, Click Here, otherwise continue to Step 8.
- Directly underneath your excel file called VBAProject(your file's name here), click the Microsoft Excel Objects folder icon to open that drop-down list.
- Within the list that appears you will see every worksheet that is in that excel file. They will be listed as such: Sheet1(NAME OF SHEET HERE) and under that will be Sheet2(NAME OF SHEET HERE). Select the sheet in which you want the macro to run and double-click that sheet.
- A new window inside the Visual Basic Editor's window will appear. In this new window, paste the code for the macro. Make sure to paste this code underneath the last line of any other code which is already in the window.
- Repeat steps b and c for every sheet you want the macro to work in. Putting the macro in one sheet will not enable it for any other sheets in the workbook.
- Go to Step 8.
- Close the Microsoft Visual Basic Editor window and save the Excel file. When you close the Visual Basic Editor window, the regular Excel window will not close.
- You are now ready to run the macro.
Similar Helpful Excel Resources
Sub Merge2MultiSheets()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
MyPath = "C:\MyPath" ' change to suit
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFilename = Dir(MyPath & "\*.xls", vbNormal)
If Len(strFilename) = 0 Then Exit Sub
Do Until strFilename = ""
Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)
Set wsSrc = wbSrc.Worksheets(1)
wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
wbSrc.Close False
strFilename = Dir()
Loop
wbDst.Worksheets(1).Delete
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
I found this code in a similar (2 year old) post by someone in this forum.
Now I think nobody will post a reply to my question in that thread, so I am starting a new one.
I am looking for a code which will move all the sheets in the directory to one single workbook and the source workbook should remain intact.
(Instead of this code I need a code which will copy all the workbooks not just one, and the code should not delete the source file or any of its contents)
I am below Zero when it comes to VBA, so please help me out.
So far my code will allow me to select text files and convert them into excel workbooks, one text file = one workbook. There may be times when 20 text files are selected and other times 10. The part I'm stuck with is taking all of the workbooks and combining all of the information into one workbook calling it "Master" and then deleting the workbooks not needed. Any help would be appreciated. Thanks in advance! Here is the code so far:
Code:
Application.ScreenUpdating = False
' File filters
Filter = "Excel Files (*.xls),*.xls," & _
"Text Files (*.txt),*.txt," & _
"All Files (*.*),*.*"
' Default filter to *.*
FilterIndex = 3
' Set Dialog Caption
Title = "Select File(s) to Open"
' Select Start Drive & Path
ChDrive ("J")
ChDir ("J:\dell\use\reports\test")
With Application
' Set File Name Array to selected Files (allow multiple)
FileName = .GetOpenFilename(Filter, FilterIndex, Title, , True)
' Reset Start Drive/Path
ChDrive (Left(.DefaultFilePath, 1))
ChDir (.DefaultFilePath)
End With
' Exit on Cancel
If Not IsArray(FileName) Then
MsgBox "No file was selected."
Exit Sub
End If
' Open Files
For i = LBound(FileName) To UBound(FileName)
'msg = msg & Filename(i) & vbCrLf ' This can be removed
Workbooks.Open FileName(i)
Set wsThis = ActiveSheet
Set myRange = wsThis.Range("A1:A5000")
numR = myRange.count
For r = 1 To numR + 1
If (wsThis.Cells(r, 2)) "Error" Then
Rows(r).Select
Selection.Delete Shift:=xlUp
r = r - 1
End If
If (wsThis.Cells(r + 1, 2)) = "" Then
Exit For
End If
Next r
Cells.Select
Cells.EntireColumn.AutoFit
Range("A1").Select
If Cells(1, 1) = "" Then
ActiveWindow.Close False
End If
Next i
Application.ScreenUpdating = True
End Sub
Hi all - I have a weekly task to combine 16 spreadsheets sent to me into one document.
Each workbook is identical containing the same format just different figures (weekly report)
Is there a quick way to combine these spreadsheets, so that rather than 16 .xls files they are one file with 16 tabs?
The current method of copy and paste works fine - but would be great if there is a process to speed this rather mundane weekly task!
Basically, what i'm trying to do is combine multiple workbooks with multiple tabs into one raw data sheet that can be used for a pivot table. this raw data sheet should live in its own workbook and be updated with new data from the pre-selected reference workbooks whenever the macro is run.
So, i am currently using 2 codes, one that pulls workbooks i select and dump them into my raw data workbook, and one that takes all the tabs in my raw data workbook and dumps them into my raw data tab. couple of problems with the first macro, one, it's restricted to macro-enabled workbooks (which i don't mind, but i'd rather it pulled any excel file) and two, it will duplicate a file i've already add to the workbook rather than updating the existing tabs for said file. the second macro runs fine, and i can live with this whole process as long as i can get help fixing the below macro to accept all types of excel files and not duplicate files i've already added to the raw data workbook, and instead update said tabs with the new info.
Any help is appreciated, here's the code:
Code:
Sub CombineWorkbooks()
Dim FilesToOpen
Dim x As Integer
On Error GoTo ErrHandler
Application.ScreenUpdating = False
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Microsoft Excel Files (*.xlsm), *.xlsm", _
MultiSelect:=True, Title:="Files to Merge")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
While x <= UBound(FilesToOpen)
Workbooks.Open Filename:=FilesToOpen(x)
Sheets().Move After:=ThisWorkbook.Sheets _
(ThisWorkbook.Sheets.Count)
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
I found the following code that merges one range from all workbooks in a folder into one new worksheet. As of now, the code is copying the range ("B4:L4") on the third tab of every workbook. Is there a way to modify this code to also copy the ranges ("P4:R4") and ("V4:AA4")? Essential I want to be able to copy multiple ranges instead of just one.
Code:
Sub MergeAllWorkbooks()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String
Dim SourceRcount As Long, FNum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
' Change this to the path\folder location of your files.
MyPath = "Z:\My Documents\Analyst Recommendations\Top Analysts\Analysts Results\JP Morgan\Test"
' Add a slash at the end of the path if needed.
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
' If there are no Excel files in the folder, exit.
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
' Fill the myFiles array with the list of Excel files
' in the search folder.
FNum = 0
Do While FilesInPath <> ""
FNum = FNum + 1
ReDim Preserve MyFiles(1 To FNum)
MyFiles(FNum) = FilesInPath
FilesInPath = Dir()
Loop
' Set various application properties.
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
' Add a new workbook with one sheet.
Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
rnum = 1
' Loop through all files in the myFiles array.
If FNum > 0 Then
For FNum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
' Change this range to fit your own needs.
With mybook.Worksheets(3)
Set sourceRange = .Range("B4:L4")
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
' If source range uses all columns then
' skip this file.
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "There are not enough rows in the target worksheet."
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
' Copy the file name in column A.
With sourceRange
BaseWks.Cells(rnum, "A"). _
Resize(.Rows.Count).Value = MyFiles(FNum)
End With
' Set the destination range.
Set destrange = BaseWks.Range("B" & rnum)
' Copy the values from the source range
' to the destination range.
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next FNum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
' Restore the application properties.
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
Hello,
I couldn't find a previous thread on this specifically. I am trying to take multiple workbooks (2nd sheet in each workbook to be exact) and copy/paste every line of data from each into a master. Column headings in each wkbk are identical. I don't think Consolidate will work unless I use a count/offset function in a named range. Any ideas on code would be much appreciated.
I just want all the worksheets from multiple workbooks from one folder in one workbook with the worksheet names changed so it includes the file name (especially since there will lots of duplication). I actually want all the data together but because formatting is confused with lots of variance including numbers of worksheets merely getting it in one workbook would be a fantastic start. Thanks in advance. I don't mind if there is a suitable thread to refer to.
Hi all,
I have been searching for ever now and can't seem to find what I am looking for...(maybe I am wording it wrong)
What I have to do is take Workbook 1 and copy all the data and paste it under all the data in Workbook 2... and do this for about 200 worksheets per workbook, all of them with the same titles.
So for example....
Take all of the rows with data in them starting with row 4, from Workbook 1, Worksheet 1 and paste them under all the rows with data in Workbook 2, Worksheet 1.
Then.... go to Worksheet 2, then Worksheet 3 and so on...
I program in Java, and know a little about VBA, but not nearly enough to get this hammered out... Any help would be greatly appreciated.
Thanks
I'm using Excel 2000 on Windows XP at work and I am trying to find a macro that can combine a bunch of different workbooks all on one worksheet.
I'm working with hundreds of exported workbooks which all have one worksheet and several hundred rows of data. Basically I want to append all the data from each workbook into a giant master file.
I was able to google from macros but none of them worked correctly.
Any help is appreciated thanks.
Hi all,
I'm trying to pull information from several different workbooks (which are invoices) into a single worksheet. I may have 40 different identical workbooks. and I'm trying to pull specific data from each of them and list them (stack) in the single worksheet.
For instance, if E13 on each of the 40 workbooks is a person's name, I'd like to drop each of those values into the combined worksheet, starting at C2 and going from there (C3, C4, etc).
Can someone point me in the right direction?
Thanks!
David
|
|