Tabellab

Paths, Separators and Checking a File Exists

Lesson 1 of 8Reading

A path is only text, and that is the problem

Every file has an address: C:\Reports\2026\March.csv on Windows, /Users/anna/Reports/March.csv on a Mac. To VBA that address is a plain String - it is not checked, not corrected and not complained about until the moment you use it. Almost every failure in file automation is a path that is slightly wrong: a doubled backslash, a missing one, a folder that moved, or a workbook that was never saved. This lesson gives you three small functions that end that whole category of bug, and one diagnostic macro that tells you where you actually are.

Run this first

Paste everything below into a standard module (Alt+F11, then Insert - Module) and press F5 inside ShowPathDiagnostics. It needs no file and creates nothing. It prints, both to the Immediate window (Ctrl+G) and to a message box, every path fact your later macros will depend on.

Option Explicit

Sub ShowPathDiagnostics()
    Dim sep As String
    Dim bookFolder As String
    Dim targetFile As String
    Dim msg As String

    sep = Application.PathSeparator
    bookFolder = ThisWorkbook.Path

    msg = "Separator on this machine: " & sep & vbCrLf

    If Len(bookFolder) = 0 Then
        msg = msg & "ThisWorkbook.Path is EMPTY - this file has never been saved." & vbCrLf
    Else
        msg = msg & "Workbook folder: " & bookFolder & vbCrLf
    End If

    msg = msg & "Workbook file:   " & ThisWorkbook.FullName & vbCrLf
    msg = msg & "Temp folder:     " & Environ$("TEMP") & vbCrLf & vbCrLf

    targetFile = JoinPath(bookFolder, "March.csv")

    msg = msg & "Looking for:  " & targetFile & vbCrLf
    msg = msg & "File found:   " & FileExists(targetFile) & vbCrLf
    msg = msg & "Folder found: " & FolderExists(bookFolder) & vbCrLf & vbCrLf
    msg = msg & "Control test, must say True: " & FileExists(ThisWorkbook.FullName)

    Debug.Print msg
    MsgBox msg, vbInformation, "Path diagnostics"
End Sub

Public Function JoinPath(ByVal folderPath As String, ByVal fileName As String) As String
    Dim sep As String

    sep = Application.PathSeparator

    If Len(folderPath) = 0 Then
        JoinPath = fileName
    ElseIf Right$(folderPath, 1) = sep Then
        JoinPath = folderPath & fileName
    Else
        JoinPath = folderPath & sep & fileName
    End If
End Function

Public Function FileExists(ByVal fullPath As String) As Boolean
    Dim found As String

    If Len(fullPath) = 0 Then Exit Function

    On Error Resume Next
    found = Dir(fullPath, vbNormal)
    On Error GoTo 0

    FileExists = (Len(found) > 0)
End Function

Public Function FolderExists(ByVal folderPath As String) As Boolean
    Dim attrFlags As Long

    If Len(folderPath) = 0 Then Exit Function

    On Error Resume Next
    attrFlags = GetAttr(folderPath)
    If Err.Number <> 0 Then
        Err.Clear
        Exit Function
    End If
    On Error GoTo 0

    FolderExists = ((attrFlags And vbDirectory) = vbDirectory)
End Function

What each piece is for

  • Application.PathSeparator returns \ on Windows and / on Mac. Use it instead of typing a backslash and your code survives the trip between platforms.
  • ThisWorkbook.Path is the folder holding the file that contains your code - and it is an empty string until the workbook has been saved at least once. Do not confuse it with ActiveWorkbook.Path, which follows whichever window is in front.
  • JoinPath glues folder and file name with exactly one separator, whether or not the folder already ends in one. That single If is the end of the C:\Reports\\March.csv bug.
  • FileExists wraps Dir, which returns the bare file name when the file is there and an empty string when it is not. VBA has no True/False version, so everybody writes this one.
  • FolderExists uses GetAttr instead, and tests the vbDirectory bit. GetAttr raises an error on a path that does not exist, which is why it sits inside On Error Resume Next - the error is the answer.
  • The control test checks ThisWorkbook.FullName, which must exist by definition. If that line says False, the problem is your environment, not your path.

The trap: Dir cannot see folders unless you ask it to

Called with one argument, Dir looks for files only. Give it a perfectly good folder and it returns an empty string, your FileExists-style check reports False, and you spend the next hour proving that a folder which is plainly there is missing. The second argument fixes it - Dir(path, vbDirectory) - but that flag also matches files, so a file of the same name would pass a folder check. That is why the function above uses GetAttr. Run this to see all three behaviours at once:

Sub TheFolderTrap()
    Dim folderPath As String

    folderPath = ThisWorkbook.Path         ' a folder that definitely exists

    Debug.Print "Plain Dir:         [" & Dir(folderPath) & "]"
    Debug.Print "Dir + vbDirectory: [" & Dir(folderPath, vbDirectory) & "]"
    Debug.Print "GetAttr:            " & FolderExists(folderPath)
End Sub

Two more edges worth knowing

  • Dir treats * and ? in a path as wildcards, so a name arriving from a network share can turn your existence check into a silent search.
  • CurDir is not your workbook's folder. It is whatever folder Excel last used, and it changes under you. Never build a path from it.

Using the helpers

Sub UseTheHelpers()
    Dim csvPath As String

    csvPath = JoinPath(ThisWorkbook.Path, "March.csv")

    If Not FileExists(csvPath) Then
        MsgBox "Put March.csv next to this workbook first:" & vbCrLf & csvPath, _
               vbExclamation
        Exit Sub
    End If

    ' ... your import code goes here, knowing the file is really there
End Sub
When a path bug has you cornered, put Debug.Print "[" & p & "]" before the failing line. The square brackets make a trailing space or an invisible line break visible, and that is what the problem usually turns out to be.

How it goes on

Everything here works on Windows and on Mac. The next lesson puts Dir in a loop to walk a whole folder, which has one rule that catches everyone: a second Dir call inside the loop resets the search. Then come the FileSystemObject (richer, but Windows-only), reading and writing text files, parsing CSV without tearing quoted fields apart, merging many exports into one sheet, and letting the user pick the file.

Who this lesson is for, and why paths break macros

This lesson is for anyone who wants a macro to work with files instead of only with cells: importing a CSV export every morning, saving a PDF of a report into the right folder, checking that all twelve monthly files have arrived before a consolidation runs. All of that starts with the same humble thing, a path, the text that says where a file lives. And all of it fails in the same humble way. The path has one backslash too many, one too few, the wrong kind of slash on a Mac, a trailing space copied from a cell, or it points at a folder that only exists on your own computer.

The frustrating part is that VBA does not check a path until you use it. You can build a completely wrong path, store it in a variable, pass it around and print it, and nothing complains. Only when you try to open the file do you get "File not found", often far away from the line that actually built the wrong text. The free lab above gives you three small helper functions, JoinPath, FileExists and FolderExists, and a diagnostic macro that shows where your workbook really is. This article explains the ideas behind them in more depth and uses them in a realistic task: checking that the files a report depends on are actually there.

The core idea: a path is text with a structure

To VBA, C:\Reports\2026\March.csv is just a String. It has a structure, though, and once you see it most path bugs become obvious. There is a folder part, C:\Reports\2026, a separator, and a file name, March.csv, which itself ends in an extension. On a Mac the same idea looks like /Users/anna/Reports/2026/March.csv, with forward slashes and no drive letter.

One path, two parts, two separatorsWindowsC:\Reports\2026\March.csvfolder = ThisWorkbook.Pathfile nameMac/Users/anna/Reports/2026/March.csvfolder = ThisWorkbook.Pathfile nameApplication.PathSeparator returns \ on Windows and / on Mac.JoinPath(folder, "March.csv") puts exactly one separator in between.Dir(fullPath) returns "March.csv" if the file exists, an empty string if not.
The same file on Windows and on Mac. The folder part is what ThisWorkbook.Path returns when the workbook sits in that folder, and the separator differs by platform.

Three rules follow from that picture. First, never type the separator yourself. Application.PathSeparator returns the right one for the machine the code is running on, so the same macro works on Windows and on Mac. Second, never glue folder and file name together with a plain &. Sometimes the folder already ends in a separator and sometimes it does not, so the safe way is a small function that adds exactly one. That is what JoinPath in the lab does. Third, never assume the file is there. Check it first, so the user gets a clear message instead of a cryptic run-time error.

There is also the question of where the macro is. ThisWorkbook.Path is the folder of the workbook that contains the code, which is almost always what you want, because you can put input files next to the workbook and find them from any computer. It is an empty string until the workbook has been saved, which is a classic surprise when testing in a brand-new workbook. ActiveWorkbook.Path follows whichever workbook happens to be in front, which changes as soon as your macro opens another file. And CurDir is the folder Excel last used in a file dialog, which has nothing to do with your workbook at all.

A worked example: has every monthly file arrived?

Imagine a small controlling team that receives one CSV export per month from the shop system and drops it into C:\Reports\2026. Before the quarterly consolidation runs, someone wants to know which files are there and which are still missing. Instead of opening Explorer and comparing by eye, we build a check sheet called FileCheck: cell B1 holds the folder, and from row 3 down, column A lists the file names we expect. The macro fills column B with the full path it built and column C with Found or Missing.

Before the macro, look at what goes wrong when paths are built by simply adding a backslash. The table compares that naive approach with JoinPath for four realistic inputs. The folder values are examples, but every one of them turns up in real workbooks.

Folder argumentFile nameWhat naive folder & "\" & name givesWhat JoinPath gives
C:\Reports\2026March.csvC:\Reports\2026\March.csvC:\Reports\2026\March.csv
C:\Reports\2026\March.csvC:\Reports\2026\\March.csv (double separator)C:\Reports\2026\March.csv
/Users/anna/Reports/2026March.csv/Users/anna/Reports/2026\March.csv (wrong separator on Mac)/Users/anna/Reports/2026/March.csv
empty (workbook never saved)March.csv\March.csv (root of the current drive)March.csv (no folder, so check the workbook is saved first)

The second row is the most common bug of all. Someone types the folder into B1 with a trailing backslash, the code adds another one, and the result contains \\. Windows often tolerates a doubled separator inside a path, but a path that starts with two backslashes is read as a network share, and comparisons such as "is this the same file?" fail because the strings differ. The last row is the unsaved-workbook case: the folder is empty, so the naive version points at the root of a drive, and JoinPath returns only the file name. Neither is what you meant, which is why the macro below checks the folder before it does anything else.

Here is the check macro. It uses JoinPath, FileExists and FolderExists exactly as they are defined in the lab, so paste it into the same module. It only reads information about files and writes results to the sheet. It never opens, moves or deletes a file.

Option Explicit

Sub CheckExpectedFiles()
    Dim ws As Worksheet
    Dim folderPath As String
    Dim fullPath As String
    Dim lastRow As Long
    Dim r As Long

    Set ws = ThisWorkbook.Worksheets("FileCheck")
    folderPath = Trim$(ws.Range("B1").Value)

    If Not FolderExists(folderPath) Then
        MsgBox "Folder not found:" & vbCrLf & "[" & folderPath & "]", vbExclamation
        Exit Sub
    End If

    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    For r = 3 To lastRow
        fullPath = JoinPath(folderPath, Trim$(ws.Cells(r, "A").Value))
        ws.Cells(r, "B").Value = fullPath
        If FileExists(fullPath) Then
            ws.Cells(r, "C").Value = "Found"
        Else
            ws.Cells(r, "C").Value = "Missing"
        End If
    Next r
End Sub

With the example folder holding January, February and March, the sheet looks like this after the run. The last row shows why the macro passes each name through Trim$: a name pasted from an email with trailing spaces would otherwise be reported as missing although the file is there.

RowA: File expectedB: Full path built by the macroC: Result
3January.csvC:\Reports\2026\January.csvFound
4February.csvC:\Reports\2026\February.csvFound
5March.csvC:\Reports\2026\March.csvFound
6April.csvC:\Reports\2026\April.csvMissing
7March.csv  (trailing spaces)C:\Reports\2026\March.csvFound, because the macro trims the name

You can cross-check the macro with worksheet formulas. Excel cannot test whether a file exists without VBA, but it can show you where the workbook is and build the same paths, which makes a mismatch visible immediately. CELL("filename",A1) only returns something once the workbook has been saved, the same rule as ThisWorkbook.Path. The example results assume Windows and a workbook saved as FileCheck.xlsm in the reports folder.

What you wantFormulaExample result
Full path of this workbook and sheet=CELL("filename",A1)C:\Reports\2026\[FileCheck.xlsm]FileCheck
Folder of this workbook (Excel 365)=TEXTBEFORE(CELL("filename",A1),"[")C:\Reports\2026\
Folder of this workbook (any version)=LEFT(CELL("filename",A1),FIND("[",CELL("filename",A1))-1)C:\Reports\2026\
Path built with a fixed separator=$B$1&"\"&A3double separator if B1 already ends in \
Path built safely=IF(RIGHT($B$1)="\",$B$1,$B$1&"\")&TRIM(A3)C:\Reports\2026\January.csv
Current directory (the CurDir trap)=INFO("directory")whatever folder Excel last used

What each check returnsPath pDir(p)Dir(p, vbDirectory)FileExists(p)FolderExists(p)…\2026\March.csvexisting file"March.csv""March.csv"TrueFalse…\2026existing folder"""2026"FalseTrue…\2026\April.csvmissing file""""FalseFalsefound / Trueempty string / FalsevbDirectory also matches files, so test folders with GetAttr and vbDirectory instead.
Four checks on three example paths. Plain Dir ignores folders, Dir with vbDirectory finds folders but also files, so the lab tests files with Dir and folders with GetAttr.

The grid is the reason the lab uses two different functions. Dir with one argument looks for files only, so it returns an empty string for a folder that plainly exists. Adding vbDirectory makes folders visible, but files still match too, so a file called 2026 would pass a folder check. GetAttr returns the attribute bits of whatever is at the path, and testing the vbDirectory bit gives a clean yes or no. When the path does not exist at all, GetAttr raises an error, and the function treats that error as the answer False.

How to do it in Excel, step by step

  1. Save the workbook as a macro-enabled file with File > Save As and the type Excel Macro-Enabled Workbook (*.xlsm). Until it is saved, ThisWorkbook.Path is empty.
  2. Rename a sheet to FileCheck (double-click the sheet tab). Type the folder path in B1 and the expected file names in A3 downwards.
  3. Press Alt+F11 to open the VBA editor and choose Insert > Module.
  4. Paste the lab code with JoinPath, FileExists and FolderExists, then paste CheckExpectedFiles below it in the same module. Keep Option Explicit once, at the very top.
  5. Run ShowPathDiagnostics from the lab first (cursor inside it, then F5). The control line must say True. If it does not, fix the environment before you go on.
  6. Press Ctrl+G to open the Immediate window and type ? JoinPath(ThisWorkbook.Path, "March.csv"), then Enter. This is the quickest way to test a helper on its own.
  7. Put the cursor inside CheckExpectedFiles and press F8 repeatedly to step through it. Hover over fullPath to see the value it built on each pass.
  8. Press F5 to run it to the end, then go back to the sheet with Alt+F11 or the Excel icon and read columns B and C.
  9. To run it from the sheet, use Developer > Macros (or Alt+F8), pick CheckExpectedFiles and click Run. If the Developer tab is hidden, switch it on under File > Options > Customize Ribbon.
On a Mac the same code works, because it uses Application.PathSeparator rather than a typed backslash. Put a Mac path such as /Users/anna/Reports/2026 in B1. Excel for Mac runs in a sandbox, so it may ask you once to grant access to a folder outside its own container.

A guard worth adding to every file macro

Most file macros assume the workbook has been saved, because they look for files next to it. A three-line guard at the top turns a confusing failure later on into a clear instruction now. It costs nothing and it saves the support question "your macro says file not found".

If Len(ThisWorkbook.Path) = 0 Then
    MsgBox "Please save this workbook first, then run the macro again.", vbExclamation
    Exit Sub
End If

VBA files, folders and CSV course illustration
This course takes your macros from one hard-coded path to whole folders of files, text and CSV.

Common mistakes, and how to spot them

  • Hard-coding the separator. A literal "\" in a path breaks on a Mac. Search your module for "\" and replace each use with Application.PathSeparator or a call to JoinPath.
  • Doubled separators. A folder typed with a trailing backslash plus a backslash added in code gives \\. Spot it by printing the path in square brackets with Debug.Print "[" & p & "]".
  • Trailing spaces and line breaks. Names copied from emails or other systems often carry an invisible space or line break. The square-bracket print reveals it, and Trim$ removes spaces (line breaks need Replace).
  • Testing an unsaved workbook. ThisWorkbook.Path is empty until the first save, so every path built from it is wrong. The lab diagnostic says so explicitly, and the guard above stops the macro early.
  • Using ActiveWorkbook or CurDir instead of ThisWorkbook. Both change while the macro runs. If a path "sometimes works", check which of the three it was built from.
  • Checking a folder with plain Dir. It returns an empty string for every folder, so the check always fails. Use FolderExists with GetAttr.
  • Wildcards in names. Dir treats * and ? as wildcards, so a name containing them turns an existence check into a search that may match a different file.

Quick reference: functions and shortcuts used

ItemTypeWhat it does
Application.PathSeparatorVBAReturns \ on Windows and / on Mac
ThisWorkbook.PathVBAFolder of the workbook that holds the code, empty until it is saved
ThisWorkbook.FullNameVBAFolder plus file name of that workbook
ActiveWorkbook.PathVBAFolder of whichever workbook is in front, which may not be yours
Dir(path)VBAReturns the file name if a matching file exists, otherwise an empty string
Dir(path, vbDirectory)VBAAlso matches folders, and still matches files
GetAttr(path)VBAReturns the attribute bits, raises an error if the path does not exist
Environ$("TEMP")VBAThe user's temp folder on Windows
Trim$(text)VBARemoves leading and trailing spaces from a name read from a cell
=CELL("filename",A1)FormulaFull path, file and sheet name of a saved workbook
Alt+F11, F5, F8, Ctrl+GShortcutVBA editor, run, step one line, Immediate window

Real-world uses

  • Pre-flight check before a consolidation. Exactly the example above: confirm that every expected export has arrived before a macro combines them, and list what is missing instead of failing halfway.
  • Templates that travel. A budget template that reads its input file from ThisWorkbook.Path works on every colleague's computer and in a synced OneDrive or SharePoint folder that is mapped locally, without anyone editing a path in the code.
  • Saving output next to the source. A report macro that saves a PDF or CSV with JoinPath(ThisWorkbook.Path, "Report_2026-03.pdf") always writes it to a predictable place.
  • Not overwriting by accident. Before saving an export, FileExists lets you ask the user or add a suffix, instead of silently replacing last month's file.
  • Mixed Windows and Mac teams. Building every path with Application.PathSeparator means one workbook serves both, which removes a whole class of "works on my machine" problems.

What you will build in the rest of this course

Lesson 1 is free. Lessons 2 to 8 are part of the paid course, available for a one-time $9.90, and each one is built around a macro you can run straight away.

Looping Through Every File in a Folder. You put Dir in a loop to list every matching file in a folder, learn the one rule that breaks most first attempts, that a second Dir call inside the loop resets the search, and use a safe two-pass pattern with wildcards.

The FileSystemObject. You meet the richer object model for the disk, with folders, files, sizes and dates as objects, and walk into subfolders. You use late binding so no reference has to be ticked, and you archive processed files by moving them instead of deleting them, because deleting from code is permanent.

Reading Text Files Line by Line. You read a file directly without opening it as a workbook, peek at headers, count rows and search log files, close the file reliably even after an error, and learn what the classic method can and cannot do with encodings.

Writing Text and CSV Files. You write fresh exports and growing log files, see the difference between Output and Append and between Print # and Write #, and export a sheet as clean CSV.

Opening and Parsing CSV Properly. You open CSV files with the right column types so IDs keep their leading zeros and codes do not turn into dates, and you see honestly what a simple Split can and cannot handle.

Importing Many Files Into One Sheet. You combine everything so far into the macro almost every team eventually needs: a folder of monthly exports stacked on one sheet, with a column saying which file each row came from.

Letting the User Choose: FileDialog. You replace hard-coded paths with file and folder pickers, allow several files at once, and handle the user pressing Cancel.

Summary

A path is text with a structure: a folder, a separator and a file name. Build it with JoinPath and Application.PathSeparator instead of typing backslashes, start from ThisWorkbook.Path rather than ActiveWorkbook or CurDir, and check with FileExists and FolderExists before you use it. In the example, that turned a manual look through a folder into a check sheet that reports Found or Missing for every expected file, and it works the same on Windows and on Mac.

Now scroll up and run ShowPathDiagnostics in the lab. Read what it says about your own machine, run TheFolderTrap to see plain Dir miss a folder that exists, and answer the check question. When paths stop being a mystery, the rest of the course, looping folders, reading and writing files and merging CSV exports, is where the real time savings start.

Frequently asked questions

How do I check if a file exists in Excel VBA?

Call Dir with the full path: it returns the file name when the file exists and an empty string when it does not. Wrap that in a small Boolean function such as FileExists so the rest of your code reads clearly.

How do I check if a folder exists in VBA?

Use GetAttr on the path and test the vbDirectory bit, with error handling because GetAttr raises an error for a path that does not exist. Plain Dir without vbDirectory ignores folders, and Dir with vbDirectory also matches files.

Why is ThisWorkbook.Path empty?

The workbook has never been saved, so it has no folder yet. Save it once and ThisWorkbook.Path returns the folder it was saved in.

What is the difference between ThisWorkbook.Path and ActiveWorkbook.Path?

ThisWorkbook is the workbook that contains the running code, ActiveWorkbook is whichever workbook is in front. They differ as soon as your macro opens another file, so file macros should normally use ThisWorkbook.

How do I make VBA file paths work on both Windows and Mac?

Never type a backslash into a path. Use Application.PathSeparator, which returns a backslash on Windows and a forward slash on Mac, ideally inside a helper such as JoinPath.

Why does my VBA path end up with two backslashes?

The folder already ended in a backslash and the code added another one. A JoinPath function that only adds a separator when the folder does not already end in one prevents it.

Keep going: Files, Folders & CSV

This free lab is lesson 1 of 8. Unlock the other 7 hands-on labs, the final exam and your certificate for a one-time $9.90.

  1. Looping Through Every File in a Folder
  2. The FileSystemObject
  3. Reading Text Files Line by Line
  4. Writing Text and CSV Files
  5. Opening and Parsing CSV Properly
  6. Importing Many Files Into One Sheet
  7. Letting the User Choose: FileDialog

Buy course β€” $9.90 See the full course

Knowledge check

You pass an existing folder path to Dir(folderPath), with no second argument. What comes back?

Continues in this course
  • Looping Through Every File in a Folder
  • The FileSystemObject
  • Reading Text Files Line by Line
  • Writing Text and CSV Files
  • Opening and Parsing CSV Properly
  • Importing Many Files Into One Sheet

Buy the course to unlock the remaining 7 lessons, the exam and the certificate.

Buy course β€” $9.90