Skip to main content

How to loop through files in a directory and copy data into a master sheet in Excel?

Supposing there are multiple Excel workbooks in a folder, and you want to loop through all these Excel files and copy data from specified range of same name worksheets into a master worksheet in Excel, what can you do? This article introduces a method to achieve it in details.

Loop through files in a directory and copy data into a master sheet with VBA code


Loop through files in a directory and copy data into a master sheet with VBA code

If you want to copy specified data in range A1:D4 from all sheet1 of workbooks in a certain folder to a master sheet, please do as follows.

1. In the workbook you will create a master worksheet, press the Alt + F11 keys to open the Microsoft Visual Basic for Applications window.

2. In the Microsoft Visual Basic for Applications window, click Insert > Module. Then copy below VBA code into the code window.

VBA code: loop through files in a folder and copy data into a master sheet

Sub Merge2MultiSheets()
    Dim xRg As Range
    Dim xSelItem As Variant
    Dim xFileDlg As FileDialog
    Dim xFileName, xSheetName, xRgStr As String
    Dim xBook, xWorkBook As Workbook
    Dim xSheet As Worksheet
    On Error Resume Next
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    Application.ScreenUpdating = False
    xSheetName = "Sheet1"
    xRgStr = "A1:D4"
    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    With xFileDlg
        If .Show = -1 Then
            xSelItem = .SelectedItems.Item(1)
            Set xWorkBook = ThisWorkbook
            Set xSheet = xWorkBook.Sheets("New Sheet")
            If xSheet Is Nothing Then
                xWorkBook.Sheets.Add(after:=xWorkBook.Worksheets(xWorkBook.Worksheets.Count)).Name = "New Sheet"
                Set xSheet = xWorkBook.Sheets("New Sheet")
            End If
            xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
            If xFileName = "" Then Exit Sub
            Do Until xFileName = ""
               Set xBook = Workbooks.Open(xSelItem & "\" & xFileName)
                Set xRg = xBook.Worksheets(xSheetName).Range(xRgStr)
                xRg.Copy xSheet.Range("A65536").End(xlUp).Offset(1, 0)
                xFileName = Dir()
                xBook.Close
            Loop
        End If
    End With
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

Note:

1). In the code, “A1:D4” and “Sheet1” mean that data in range A1:D4 of all Sheet1 will be copied into the master sheet. And “New Sheet” is the name of the new created master sheet.
2). The Excel files in the specific folder should not open.

3. Press the F5 key to run the code.

4. In the opening Browse window, please select the folder contains the files you will loop through, and then click the OK button. See screenshot:

Then a master worksheet named “New Sheet” is created at the end of current workbook. And data in range A1:D4 of all Sheet1 in selected folder is listed inside the worksheet.


Related articles:

Best Office Productivity Tools

🤖 Kutools AI Aide: Revolutionize data analysis based on: Intelligent Execution   |  Generate Code  |  Create Custom Formulas  |  Analyze Data and Generate Charts  |  Invoke Kutools Functions
Popular Features: Find, Highlight or Identify Duplicates   |  Delete Blank Rows   |  Combine Columns or Cells without Losing Data   |   Round without Formula ...
Super Lookup: Multiple Criteria VLookup    Multiple Value VLookup  |   VLookup Across Multiple Sheets   |   Fuzzy Lookup ....
Advanced Drop-down List: Quickly Create Drop Down List   |  Dependent Drop Down List   |  Multi-select Drop Down List ....
Column Manager: Add a Specific Number of Columns  |  Move Columns  |  Toggle Visibility Status of Hidden Columns  |  Compare Ranges & Columns ...
Featured Features: Grid Focus   |  Design View   |   Big Formula Bar    Workbook & Sheet Manager   |  Resource Library (Auto Text)   |  Date Picker   |  Combine Worksheets   |  Encrypt/Decrypt Cells    Send Emails by List   |  Super Filter   |   Special Filter (filter bold/italic/strikethrough...) ...
Top 15 Toolsets12 Text Tools (Add Text, Remove Characters, ...)   |   50+ Chart Types (Gantt Chart, ...)   |   40+ Practical Formulas (Calculate age based on birthday, ...)   |   19 Insertion Tools (Insert QR Code, Insert Picture from Path, ...)   |   12 Conversion Tools (Numbers to Words, Currency Conversion, ...)   |   7 Merge & Split Tools (Advanced Combine Rows, Split Cells, ...)   |   ... and more

Supercharge Your Excel Skills with Kutools for Excel, and Experience Efficiency Like Never Before. Kutools for Excel Offers Over 300 Advanced Features to Boost Productivity and Save Time.  Click Here to Get The Feature You Need The Most...

Description


Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier

  • Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
  • Open and create multiple documents in new tabs of the same window, rather than in new windows.
  • Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!
Comments (22)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Good afternoon. I urgently need your help: what VBA code could I use to copy a folder from an Excel workbook and paste it into an existing Excel workbook in another workbook? Would it be possible to copy the formatting just from the formatting?
This comment was minimized by the moderator on the site
Boa tarde. Preciso urgentemente de sua ajuda: qual código de VBA poderia utilizar para copiar a uma planilha inteira de uma pasta de trabalho Excel e colar em várias outras pastas de trabalho Excel já existentes em uma em um mesmo diretório? Teria como copiar apenas a formatação da planilha inteira?
This comment was minimized by the moderator on the site
My scenario is similar, except I have multiple sheets in each file, all with different names but consistent between files. Is there a way to Loop this code to copy the data within the files and paste (values) to specific sheet names in the master workbook? The sheet names in the master are the same as in the files. I want to loop through them. Also, the amount of data in each sheet will vary, so I will need to select the data in each sheet using something like this:

Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select


File sheet names are Giving, Services, Insurance, Car, Other Expenses, etc...

Thanks in advance.
This comment was minimized by the moderator on the site
Hi Andrew Shahan,
The following VBA code can solve your problem. After running the code and selecting a folder, the code will automatically match the worksheet by name and paste the data into the worksheet of the same name in the master workbook.
Sub Merge2MultiSheets()
'Updated by Extendoffice 20221209
    Dim xRg As Range
    Dim xSelItem As Variant
    Dim xFileDlg As FileDialog
    Dim xFileName, xSheetName, xRgStr As String
    Dim xBook As Workbook, xMainBook As Workbook
    Dim xSheet As Worksheet
    On Error Resume Next
    
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    Application.ScreenUpdating = False

    Set xMainBook = ThisWorkbook
    
    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    With xFileDlg
        If .Show = -1 Then
            xSelItem = .SelectedItems.Item(1)
            xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
            If xFileName = "" Then Exit Sub
            
            Do Until xFileName = ""
            Set xBook = Workbooks.Open(xSelItem & "\" & xFileName)

            For Start = 1 To xBook.Worksheets.Count
                Set xSheet = xBook.Worksheets.Item(Start)
                xSheet.Activate
                xSheetName = xSheet.Name
                xSheet.UsedRange.Copy (xMainBook.Worksheets.Item(xSheetName).Range("A1048576").End(xlUp).Offset(1, 0))
            Next
                xFileName = Dir()
                xBook.Close
            Loop
        End If
    End With
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Olá bom dia.
Gostei muito dessde código, mas não me ajudou com os relatórios que eu preciso impreimir.
Preciso imprimir 2.400 relatório de exel que estão em pastas diferentes e não estão configuradas corretamente para impressão. Pode me enviar um códgo de VBA que automatize essas impressões ? Me ajudaria muito, obrigada.
This comment was minimized by the moderator on the site
Hi Maria Soares,
Please check if the VBA code in the following post can help.
How to print multiple workbooks in Excel?
This comment was minimized by the moderator on the site
Hi i want a code to copy the data in 6 different workbooks(in a folder) which has sheets included in them to NEW WORKBOOK. in vba
plz help me asp
This comment was minimized by the moderator on the site
Hi Paranusha,
The VBA script in the following article can combine multiple workbooks or specified sheets of workbooks to a master workbook. Please check if it can help.
How To Combine Multiple Workbooks Into One Master Workbook In Excel?
This comment was minimized by the moderator on the site
for me, the "Sheet1" tab name changes for each of my files. For instance, Tab1, Tab2, Tab3, Tab4...How can I setup a loop to run through a list in excel and keep changing the "Sheet1" name until it runs through everything?
This comment was minimized by the moderator on the site
Hi Nick,The VBA code below can help you solve the problem. Please have a try.<div data-tag="code">Sub LoopThroughFileRename()
'Updated by Extendofice 2021/12/31
Dim xRg As Range
Dim xSelItem As Variant
Dim xFileDlg As FileDialog
Dim xFileName, xSheetName, xRgStr As String
Dim xBook, xWorkBook As Workbook
Dim xSheet As Worksheet
Dim xShs As Sheets
Dim xName As String
Dim xFNum As Integer
On Error Resume Next
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
xFileDlg.Show
xSelItem = xFileDlg.SelectedItems.Item(1)
xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
Do While xFileName <> ""
Set xWorkBook = Workbooks.Open(xSelItem & "\" & xFileName)
Set xShs = xWorkBook.Sheets
For xFNum = 1 To xShs.Count
Set xSheet = xShs.Item(xFNum)
xName = xSheet.Name
xName = Replace(xName, "Sheet", "Tab") 'Replace Sheet with Tab
xSheet.Name = xName
Next
xWorkBook.Save
xWorkBook.Close
xFileName = Dir()
Loop
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
how do you make to code leave a blank if cell is empty?
This comment was minimized by the moderator on the site
Thank you - how would one be able to copy and paste (special values) from each worksheet within a workbook into separate sheets within a main Master file?
This comment was minimized by the moderator on the site
Hi - This code works very well for the first 565 lines for every file, but all lines after are overlapped by the next file.
is there a way to fix this?
This comment was minimized by the moderator on the site
Hi - This code is perfect for what I'm trying to achieve.

Is there a way to loop through all folders and subfolders and perform the copy?


Thanks!
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations