VBA course · Lesson 27 of 33

Files and folders: open, save, loop through files and write text files

Loop through every workbook in a folder with Dir, let users pick folders with FileDialog, save as .xlsm or PDF, copy and delete files and read text files.

Advanced 22 min read

Sooner or later every automation project leaves the single workbook and starts working with files: forty branch reports that arrive every Monday, a folder of CSV exports, one PDF per customer that has to be saved somewhere sensible. In this lesson you learn the VBA tools for that work: how to find files, how to let the user pick a folder, how to open, save and close workbooks safely, how to copy, rename and delete files, and how to read and write plain text files.

You should already be comfortable with workbook and worksheet objects from Workbooks and worksheets in VBA, with loops from Do loops: Do While, Do Until and Exit Do and with error handling from Error handling and debugging in VBA. All three come together here.

Building paths that work everywhere

A path is the address of a file: the folder plus the file name, for example C:\Reports\2026\North.xlsx. On Windows the folders are separated by a backslash; on a Mac by a forward slash (/Users/anna/Reports/North.xlsx). If you glue paths together with a hard-coded "\", your macro breaks on a Mac. Use Application.PathSeparator instead, which returns the right character for the computer the code runs on.

VBA
Option Explicit

Sub ShowPathParts()
    Dim sep As String
    Dim folderPath As String
    Dim fullName As String

    sep = Application.PathSeparator
    ' The folder that contains this workbook, e.g. C:\Work
    folderPath = ThisWorkbook.Path
    fullName = folderPath & sep & "Branch reports" & sep & "North.xlsx"

    Debug.Print "Folder: "; folderPath
    Debug.Print "Full path: "; fullName

    ' Dir returns "" when nothing matches
    If Dir(fullName) = "" Then
        Debug.Print "The file does not exist yet."
    Else
        Debug.Print "Found it."
    End If

    ' vbDirectory makes Dir look for folders too
    If Dir(folderPath & sep & "Branch reports", vbDirectory) = "" Then
        Debug.Print "The folder is missing."
    End If
End Sub
Build a path from parts and check whether the folder and file exist

ThisWorkbook.Path is the folder of the workbook that holds the code, which is the safest starting point: if you keep the macro file next to its data, the macro keeps working when the whole folder moves to another drive. ThisWorkbook.FullName gives the path plus the file name. A brand-new workbook that has never been saved has an empty Path, so check for that if your macro could run from an unsaved file.

Note. If the workbook is stored in OneDrive or SharePoint, ThisWorkbook.Path can return a web address that starts with https://. Dir, Kill and the other file commands cannot work with such an address. Either open the file from a locally synced folder or let the user pick the folder with a FileDialog, which returns a normal local path.

Looping through files with Dir

Dir is the classic tool for finding files. You call it once with a pattern such as "C:\Reports\*.xlsx"; it returns the first matching file name (only the name, not the folder). Then you call Dir again without arguments and it returns the next match, and so on, until it returns an empty string. The * wildcard means "any characters" and ? means "exactly one character".

VBA
Option Explicit

Sub ListWorkbooksInFolder()
    Dim folderPath As String
    Dim fileName As String
    Dim ws As Worksheet
    Dim r As Long

    folderPath = ThisWorkbook.Path & Application.PathSeparator
    Set ws = ThisWorkbook.Worksheets.Add
    ws.Range("A1:B1").Value = Array("File", "Last modified")
    r = 2

    fileName = Dir(folderPath & "*.xls*")
    Do While fileName <> ""
        ' Skip the workbook that is running this code
        If fileName <> ThisWorkbook.Name Then
            ws.Cells(r, 1).Value = fileName
            ws.Cells(r, 2).Value = FileDateTime(folderPath & fileName)
            r = r + 1
        End If
        fileName = Dir   ' next match
    Loop

    ws.Columns("A:B").AutoFit
    MsgBox r - 2 & " file(s) listed.", vbInformation
End Sub
List every Excel file in a folder on a new sheet

The pattern *.xls* matches .xls, .xlsx, .xlsm and .xlsb. FileDateTime returns the date and time a file was last saved, and FileLen returns its size in bytes.

Watch out. Dir keeps only one search in memory. If you call Dir with a new pattern inside the loop (for example to check that an output file exists), the outer search is lost and the loop stops early or skips files. Collect the file names into an array or collection first, then process them in a second loop.

Letting the user pick a folder or file

Hard-coded paths are fine for your own macros, but colleagues keep their files elsewhere. Application.FileDialog shows the normal Office open dialog and returns what the user selected.

VBA
Option Explicit

Function PickFolder(ByVal title As String) As String
    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFolderPicker)
    With fd
        .Title = title
        .AllowMultiSelect = False
        ' Show returns -1 when the user clicks OK, 0 on Cancel
        If .Show = -1 Then
            PickFolder = .SelectedItems(1)
        Else
            PickFolder = ""
        End If
    End With
End Function

Sub TestPickFolder()
    Dim f As String
    f = PickFolder("Choose the folder with the branch reports")
    If f = "" Then
        MsgBox "Cancelled."
    Else
        MsgBox "You chose: " & f
    End If
End Sub
Ask for a folder; return "" if the user cancels

For files use msoFileDialogFilePicker and add a filter so only workbooks are shown. With AllowMultiSelect = True the user can pick several files with Ctrl (Cmd) and you loop through .SelectedItems.

VBA
Option Explicit

Sub PickWorkbooks()
    Dim fd As FileDialog
    Dim i As Long
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    With fd
        .Title = "Select the monthly exports"
        .AllowMultiSelect = True
        .Filters.Clear
        .Filters.Add "Excel workbooks", "*.xlsx; *.xlsm; *.xls"
        If .Show <> -1 Then Exit Sub
        For i = 1 To .SelectedItems.Count
            Debug.Print .SelectedItems(i)
        Next i
    End With
End Sub
Pick one or more workbooks and print their full paths

The older Application.GetOpenFilename also works and returns False on cancel; FileDialog is more flexible and gives you the folder picker, which GetOpenFilename lacks. On a Mac both dialogs work, but filters are less reliable; if the filter misbehaves, drop it and check the extension in code.

Opening, saving and closing workbooks

Workbooks.Open opens a file and returns the Workbook object, so always store it in a variable rather than relying on ActiveWorkbook. Useful arguments are ReadOnly:=True (you only want to read it, and nobody else is blocked) and UpdateLinks:=0 (do not ask about external links).

When you are done, Close SaveChanges:=False closes without saving and without a prompt; SaveChanges:=True saves first. Leaving out the argument makes Excel ask the user, which interrupts an automated run.

Save, SaveAs and SaveCopyAs

  • wb.Save saves under the current name and format.
  • wb.SaveAs fileName, FileFormat saves under a new name, and the open workbook now is that new file.
  • wb.SaveCopyAs fileName writes a copy to disk; the open workbook keeps its old name. Perfect for backups. It always keeps the original format, so give the copy the same extension.

The FileFormat argument decides the file type. Always pass it explicitly with SaveAs, otherwise Excel may refuse to save macros into an .xlsx name or save in the wrong format.

ConstantValueExtension
xlOpenXMLWorkbook51.xlsx (no macros)
xlOpenXMLWorkbookMacroEnabled52.xlsm
xlExcel1250.xlsb
xlCSVUTF862.csv in UTF-8
VBA
Option Explicit

Sub BackupAndExport()
    Dim stamp As String
    Dim backupName As String
    Dim shareName As String
    Dim sep As String

    sep = Application.PathSeparator
    stamp = Format(Now, "yyyy-mm-dd_hhmm")

    ' 1. Backup copy, same format as this file (.xlsm)
    backupName = ThisWorkbook.Path & sep & "Backup_" & stamp & ".xlsm"
    ThisWorkbook.SaveCopyAs backupName

    ' 2. Copy the Report sheet into a new workbook and save it as .xlsx
    ThisWorkbook.Worksheets("Report").Copy   ' creates a new workbook
    shareName = ThisWorkbook.Path & sep & "Report_" & stamp & ".xlsx"
    Application.DisplayAlerts = False        ' no "file exists" prompt
    ActiveWorkbook.SaveAs fileName:=shareName, FileFormat:=xlOpenXMLWorkbook
    ActiveWorkbook.Close SaveChanges:=False
    Application.DisplayAlerts = True

    MsgBox "Backup and report saved in " & ThisWorkbook.Path
End Sub
Save a timestamped backup, then save a macro-free copy for sharing

Worksheet.Copy without arguments copies the sheet into a brand-new workbook, which becomes the active workbook; this is one of the few places where using ActiveWorkbook straight away is reasonable. Setting DisplayAlerts to False silences the "do you want to replace it?" question; always switch it back on.

Saving as PDF

ExportAsFixedFormat turns a sheet, a range or a whole workbook into a PDF. It uses the page setup of the sheet (orientation, margins, print area), so set those first if the layout matters.

VBA
Option Explicit

Sub SaveInvoiceAsPdf()
    Dim pdfName As String
    pdfName = ThisWorkbook.Path & Application.PathSeparator & _
        "Invoice_" & ThisWorkbook.Worksheets("Invoice").Range("F2").Value & ".pdf"

    ThisWorkbook.Worksheets("Invoice").ExportAsFixedFormat _
        Type:=xlTypePDF, _
        fileName:=pdfName, _
        Quality:=xlQualityStandard, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
End Sub
Export the Invoice sheet as a PDF next to the workbook

Project: combine every branch file into one sheet

Here is the classic job. A folder holds one workbook per branch, each with a sheet called Sales laid out the same way (headers in row 1, data below). The macro opens each file read-only, copies the data rows under each other on a Combined sheet, adds a column with the source file name and closes the file again.

ABCD
1DateProductUnitsRevenue
22026-03-02Keyboard12300
32026-03-02Mouse30360
42026-03-03Monitor4760

Before: North.xlsx, sheet Sales (South.xlsx looks the same with its own rows)

VBA
Option Explicit

Sub CombineBranchFiles()
    Dim folderPath As String
    Dim fileName As String
    Dim files As New Collection
    Dim item As Variant
    Dim wbSrc As Workbook
    Dim wsOut As Worksheet
    Dim srcData As Range
    Dim nextRow As Long
    Dim lastRow As Long

    folderPath = PickFolder("Folder with the branch workbooks")
    If folderPath = "" Then Exit Sub
    folderPath = folderPath & Application.PathSeparator

    ' 1. Collect the file names first (Dir cannot be nested)
    fileName = Dir(folderPath & "*.xlsx")
    Do While fileName <> ""
        files.Add fileName
        fileName = Dir
    Loop
    If files.Count = 0 Then
        MsgBox "No .xlsx files in that folder.", vbExclamation
        Exit Sub
    End If

    ' 2. Prepare the output sheet
    Set wsOut = ThisWorkbook.Worksheets("Combined")
    wsOut.Cells.Clear
    wsOut.Range("A1:E1").Value = Array("Date", "Product", "Units", "Revenue", "Branch file")
    nextRow = 2

    Application.ScreenUpdating = False
    On Error GoTo CleanFail

    ' 3. Open each file, copy its data block, close it
    For Each item In files
        Set wbSrc = Workbooks.Open(fileName:=folderPath & item, ReadOnly:=True, UpdateLinks:=0)
        With wbSrc.Worksheets("Sales")
            lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
            If lastRow >= 2 Then
                Set srcData = .Range("A2:D" & lastRow)
                ' Copy values only, without the clipboard
                wsOut.Cells(nextRow, 1).Resize(srcData.Rows.Count, 4).Value = srcData.Value
                wsOut.Cells(nextRow, 5).Resize(srcData.Rows.Count, 1).Value = item
                nextRow = nextRow + srcData.Rows.Count
            End If
        End With
        wbSrc.Close SaveChanges:=False
        Set wbSrc = Nothing
    Next item

    Application.ScreenUpdating = True
    MsgBox files.Count & " files combined, " & nextRow - 2 & " rows.", vbInformation
    Exit Sub

CleanFail:
    If Not wbSrc Is Nothing Then wbSrc.Close SaveChanges:=False
    Application.ScreenUpdating = True
    MsgBox "Stopped at " & item & ": " & Err.Description, vbCritical
End Sub
Combine the Sales sheet of every workbook in a chosen folder

This sample calls the PickFolder function from earlier, so keep both in the same module. Notice the details that make it robust: the file list is collected before anything is opened; data is copied with .Value = .Value, which is faster than Copy/Paste and leaves the clipboard alone (see Make your macros fast: speed optimization in VBA); the last row is found per file (Find the last row and build dynamic ranges in VBA); and the error handler closes a file that was left open.

ABCDE
1DateProductUnitsRevenueBranch file
22026-03-02Keyboard12300North.xlsx
32026-03-02Mouse30360North.xlsx
42026-03-03Monitor4760North.xlsx
52026-03-02Keyboard7175South.xlsx

After: the Combined sheet (first rows)

Copying, renaming and deleting files

VBA has small built-in statements for file housekeeping. They act immediately and cannot be undone, so test them on a copy.

StatementWhat it doesExample
MkDirCreates one folder (the parent must exist)MkDir "C:\Reports\2026"
FileCopyCopies a closed fileFileCopy src, dest
Name ... AsRenames or moves a fileName oldPath As newPath
KillDeletes files, wildcards allowedKill "C:\Temp\*.tmp"
RmDirRemoves an empty folderRmDir "C:\Temp\Old"
VBA
Option Explicit

Sub ArchivePdfs()
    Dim baseFolder As String
    Dim archiveFolder As String
    Dim fileName As String
    Dim sep As String

    sep = Application.PathSeparator
    baseFolder = ThisWorkbook.Path & sep & "Invoices" & sep
    archiveFolder = baseFolder & "Archive " & Format(DateAdd("m", -1, Date), "yyyy-mm") & sep

    Dim pdfs As New Collection
    Dim item As Variant

    ' Create the archive folder only if it is missing
    If Dir(archiveFolder, vbDirectory) = "" Then MkDir archiveFolder

    ' 1. Collect the names first
    fileName = Dir(baseFolder & "*.pdf")
    Do While fileName <> ""
        pdfs.Add fileName
        fileName = Dir
    Loop

    ' 2. Now it is safe to call Dir again for each file
    For Each item In pdfs
        ' Name ... As moves the file; it fails if the target already exists
        If Dir(archiveFolder & item) = "" Then
            Name baseFolder & item As archiveFolder & item
        End If
    Next item
End Sub
Archive last month's PDFs into a dated subfolder

The check Dir(archiveFolder & item) is itself a Dir call. Had it been inside the first loop, it would have reset the search for PDFs, which is exactly the trap described earlier. Collecting the names first, then acting on them, avoids the problem completely. DateAdd("m", -1, Date) gives the same day last month, which Format turns into a label such as 2026-11 (Working with dates and times in VBA).

FileCopy fails with an error if the source file is open in Excel. To copy an open workbook use SaveCopyAs instead.

FileSystemObject (Windows)

The FileSystemObject (FSO) from the Microsoft Scripting Runtime offers an object-oriented way to work with drives, folders and files, including subfolders, which Dir handles poorly. Create it with late binding (CreateObject) so you do not need to set a reference (Control Outlook, Word and PowerPoint from Excel VBA explains binding).

VBA
Option Explicit

Sub ListAllFilesRecursive()
    Dim fso As Object
    Dim ws As Worksheet
    Dim r As Long
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ws = ThisWorkbook.Worksheets.Add
    ws.Range("A1:C1").Value = Array("Folder", "File", "Size (KB)")
    r = 2
    ListFolder fso.GetFolder(ThisWorkbook.Path), ws, r
    ws.Columns("A:C").AutoFit
End Sub

Private Sub ListFolder(ByVal fld As Object, ByVal ws As Worksheet, ByRef r As Long)
    Dim f As Object
    Dim subFld As Object
    For Each f In fld.Files
        ws.Cells(r, 1).Value = fld.Path
        ws.Cells(r, 2).Value = f.Name
        ws.Cells(r, 3).Value = Round(f.Size / 1024, 1)
        r = r + 1
    Next f
    ' Call itself for each subfolder (recursion)
    For Each subFld In fld.SubFolders
        ListFolder subFld, ws, r
    Next subFld
End Sub
List all files in a folder and its subfolders with FSO (Windows only)

ListFolder calls itself for every subfolder; this is called recursion and is the natural way to walk a folder tree. The row counter is passed ByRef so every level writes below the previous one (Functions and Subs: parameters, ByVal, ByRef and return values).

Watch out. FileSystemObject does not exist on a Mac. CreateObject("Scripting.FileSystemObject") raises error 429 there. If your workbook must run on both systems, stick to Dir, MkDir, FileCopy, Name and Kill.

Reading and writing text files

For CSV logs and simple exports, VBA's own file statements are enough. You open a file with a file number from FreeFile, write with Print #, read with Line Input # and close with Close #.

VBA
Option Explicit

Sub WriteAndReadCsv()
    Dim fNum As Integer
    Dim path As String
    Dim lineText As String
    Dim r As Long

    path = ThisWorkbook.Path & Application.PathSeparator & "staff_export.csv"

    ' For Output creates or overwrites; use For Append to add to the end
    fNum = FreeFile
    Open path For Output As #fNum
    Print #fNum, "EmployeeID,Name,Department"
    With ThisWorkbook.Worksheets("Staff")
        For r = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
            Print #fNum, .Cells(r, 1).Value & "," & .Cells(r, 2).Value & "," & .Cells(r, 3).Value
        Next r
    End With
    Close #fNum

    ' Read it back
    fNum = FreeFile
    Open path For Input As #fNum
    Do While Not EOF(fNum)
        Line Input #fNum, lineText
        Debug.Print lineText
    Loop
    Close #fNum
End Sub
Write a CSV export, then read it back line by line

These statements write in the system's ANSI code page, so accented names such as "Zoë" may come out wrong in other programs. For proper UTF-8 text, save a sheet with FileFormat:=xlCSVUTF8 instead, or on Windows use the ADODB.Stream object.

Mac notes

  • Use Application.PathSeparator; paths look like /Users/anna/Documents/Reports.
  • Excel for Mac is sandboxed. The first time a macro opens or saves a file in a new folder, macOS may ask the user to grant access. A macro that runs unattended can stop at this prompt. Files inside ~/Library/Group Containers/UBF8T346G9.Office need no permission.
  • Dir with wildcards like *.xlsx works in current Mac versions, but older versions needed MacID. Test on the real machine.
  • FileSystemObject is not available; FileDialog works.

Common mistakes

  • Calling Dir with a new pattern inside a Dir loop, which silently breaks the outer search.
  • Forgetting the separator: folderPath & fileName without a backslash produces C:\ReportsNorth.xlsx.
  • Closing without SaveChanges, which pops up a prompt in the middle of a 200-file run.
  • Calling SaveAs with an .xlsm name but no FileFormat, which raises an error or saves the wrong type.
  • Leaving DisplayAlerts off after an error, so the user later loses work without a warning.

Check yourself

1. What does Dir return when no more files match the pattern?

2. Which FileFormat value saves a macro-enabled workbook (.xlsm)?

3. You want a backup of the open workbook without changing which file you are working in. What do you use?

4. Why is Application.PathSeparator better than a hard-coded backslash?

5. Which object is not available in Excel for Mac?