Tip: Other languages are Google-Translated. You can visit the English version of this link.
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!


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:



Recommended Productivity Tools for Excel

Kutools for Excel Helps You Always Finish Work Ahead of Time, and Stand Out From Crowd

  • More than 300 powerful advanced features, designed for 1500 work scenarios, increasing productivity by 70%, give you more time to take care of family and enjoy life.
  • No longer need memorizing formulas and VBA codes, give your brain a rest from now on.
  • Become an Excel expert in 3 minutes, Complicated and repeated operations can be done in seconds, 
  • Reduce thousands of keyboard & mouse operations every day, say goodbye to occupational diseases now.
  • 110,000 highly effective people and 300+ world-renowned companies' choice.
  • 60-day full features free trial. 60-day money back guarantees. 2 years of free upgrade and support.

Brings Tabbed Browsing and Editing to Microsoft Office, Far More Powerful Than The Browser's Tabs

  • Office Tab is designed for Word, Excel, PowerPoint and Other Office Applications: 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!
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.
    Trish · 27 days 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.
    Robertson · 2 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 · 3 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 · 6 months 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 · 4 months 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