Log in
x
or
x
x
Register
x

or

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


Easily copy/import data from a closed workbook into a master worksheet:

With the Insert File at Cursor utility of Kutools for Excel, you can easily copy data from a specified worksheet of a closed workbook into an opened workbook. See screenshot:

Kutools for Excel: with more than 200 handy Excel add-ins, free to try with no limitation in 60 days. Download and free trial Now!

Office Tab Enable Tabbed Editing and Browsing in Office, and Make Your Work Much Easier...
Kutools for Excel Solves Most of Your Problems, and Increases Your Productivity by 80%
  • Reuse Anything: Add the most used or complex formulas, charts and anything else to your favorites, and quickly reuse them in the future.
  • More than 20 text features: Extract Number from Text String; Extract or Remove Part of Texts; Convert Numbers and Currencies to English Words.
  • Merge Tools: Multiple Workbooks and Sheets into One; Merge Multiple Cells/Rows/Columns Without Losing Data; Merge Duplicate Rows and Sum.
  • Split Tools: Split Data into Multiple Sheets Based on Value; One Workbook to Multiple Excel, PDF or CSV Files; One Column to Multiple Columns.
  • Paste Skipping Hidden/Filtered Rows; Count And Sum by Background Color; Send Personalized Emails to Multiple Recipients in Bulk.
  • Super Filter: Create advanced filter schemes and apply to any sheets; Sort by week, day, frequency and more; Filter by bold, formulas, comment...
  • More than 300 powerful features; Works with Office 2007-2019 and 365; Supports all languages; Easy deploying in your enterprise or organization.

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:


The Best Office Productivity Tools

Kutools for Excel Solves Most of Your Problems, and Increases Your Productivity by 80%

  • Reuse: Quickly insert complex formulas, charts and anything that you have used before; Encrypt Cells with password; Create Mailing List and send emails...
  • Super Formula Bar (easily edit multiple lines of text and formula); Reading Layout (easily read and edit large numbers of cells); Paste to Filtered Range...
  • Merge Cells/Rows/Columns without losing Data; Split Cells Content; Combine Duplicate Rows/Columns... Prevent Duplicate Cells; Compare Ranges...
  • Select Duplicate or Unique Rows; Select Blank Rows (all cells are empty); Super Find and Fuzzy Find in Many Workbooks; Random Select...
  • Exact Copy Multiple Cells without changing formula reference; Auto Create References to Multiple Sheets; Insert Bullets, Check Boxes and more...
  • Extract Text, Add Text, Remove by Position, Remove Space; Create and Print Paging Subtotals; Convert Between Cells Content and Comments...
  • Super Filter (save and apply filter schemes to other sheets); Advanced Sort by month/week/day, frequency and more; Special Filter by bold, italic...
  • Combine Workbooks and WorkSheets; Merge Tables based on key columns; Split Data into Multiple Sheets; Batch Convert xls, xlsx and PDF...
  • More than 300 powerful features. Supports Office/Excel 2007-2019 and 365. Supports all languages. Easy deploying in your enterprise or organization. Full features 30-day free trial. 60-day money back guarantee.
kte tab 201905

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!
officetab bottom
Say something here...
symbols left.
You are guest ( Sign Up? )
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    Alexander Høgh · 8 days ago
    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?
  • To post as a guest, your comment is unpublished.
    Dan Tran · 5 months ago
    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!
  • To post as a guest, your comment is unpublished.
    Dan · 5 months ago
    Hi Thanks for this.


    How do I include the code to loop through all folders and subfolders and perform the above copy?


    Thanks!
  • To post as a guest, your comment is unpublished.
    Trish · 8 months ago
    Hi there, This works great. Is there a way to change to just pull over the values and not the formula?
    Thanks!!
    • To post as a guest, your comment is unpublished.
      crystal · 5 months ago
      Hi Trish,
      The following code can help you solve the problem. Thank you for your comment.

      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
      Set xRg = xSheet.UsedRange
      xRg.ClearFormats
      xRg.UseStandardHeight = True
      xRg.UseStandardWidth = True
      Application.DisplayAlerts = True
      Application.EnableEvents = True
      Application.ScreenUpdating = True
      End Sub
  • To post as a guest, your comment is unpublished.
    Robertson · 9 months ago
    Hello,

    Thank you for the tutorial.

    How would I: Only copy the row in "Sheet1" with values from the "total" row and paste with [filename] in master worksheet named “New Sheet”. Noting the row with Total can be different in each worksheet.

    For example:
    File1: Sheet1
    Col1,Col2,Colx
    1,2,15
    Result,10,50

    File2: Sheet1
    Col1,Col2,Colx
    1,5,10
    2,4,16
    3,3,6
    4,5,6
    5,7,10
    Result,300,500

    MasterFile: "New Sheet":
    file1, 10, 50
    file2, 300, 500
  • To post as a guest, your comment is unpublished.
    Paul Gill · 10 months ago
    Hi, thanks for the code. Please can you let me know how I can include the Excel file name from which the data range was copied? This would be a great help!

    Thank you.
  • To post as a guest, your comment is unpublished.
    Lai Ling · 1 years ago
    thank you for the vba code! It works perfectly! Would like to know what is the code if i need to PASTE AS VALUE instead? Thx in advance!
    • To post as a guest, your comment is unpublished.
      crystal · 1 years ago
      Hi Lai Ling,
      The following code can help you solve the problem. Thank you for your comment.

      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
      Set xRg = xSheet.UsedRange
      xRg.ClearFormats
      xRg.UseStandardHeight = True
      xRg.UseStandardWidth = True
      Application.DisplayAlerts = True
      Application.EnableEvents = True
      Application.ScreenUpdating = True
      End Sub