VBA: Loop Through Every File in a Folder (and Combine Them)

📎 This article includes 1 downloadable practice file ↓

⏱ 2 min readUpdated 28 September 2026

Twenty regional files land in a folder every month and someone copies them into one sheet by hand. This macro does it in seconds.

In this article
  1. How Dir works
  2. The complete macro
  3. What each part does

How Dir works

Dir("C:\Reports\*.xlsx") returns the first matching file name. Calling Dir again with no arguments returns the next one, and an empty string when there are none left.

The complete macro

Sub CombineFolder()
    Dim folder As String, f As String
    Dim wb As Workbook, master As Worksheet
    Dim nextRow As Long, lastRow As Long

    folder = "C:\Reports\"                        ' keep the trailing \
    Set master = ThisWorkbook.Sheets("Master")
    nextRow = master.Cells(master.Rows.Count, 1).End(xlUp).Row + 1

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    f = Dir(folder & "*.xlsx")
    Do While f <> ""
        Set wb = Workbooks.Open(folder & f, ReadOnly:=True)
        With wb.Sheets(1)
            lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
            If lastRow > 1 Then
                .Range("A2:F" & lastRow).Copy master.Cells(nextRow, 1)
                master.Cells(nextRow, 7).Resize(lastRow - 1).Value = f   ' source file name
                nextRow = nextRow + lastRow - 1
            End If
        End With
        wb.Close SaveChanges:=False
        f = Dir()
    Loop

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    MsgBox "Done: " & nextRow - 2 & " rows in Master", vbInformation
End Sub

What each part does

  • ScreenUpdating = False stops Excel redrawing for every file — often 5–10× faster.
  • ReadOnly:=True means a file someone else has open will not block the macro.
  • Column G records which file each row came from, so you can trace a number back.
💡 Let the user choose the folder: With Application.FileDialog(msoFileDialogFolderPicker): If .Show Then folder = .SelectedItems(1) & "\": End With
⚠️ If a macro stops halfway, ScreenUpdating stays off. Add error handling that turns it back on — see VBA error handling.

📎 Practice files for this article

  • 📗
    Combine-a-folder workbook (.xlsm)Step 1 creates 5 sample regional files; Step 2 combines them into Master with the source file name. Save the workbook in its own folder first.
    ⬇ XLSM · 20 KB

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong