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.
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 argument | File name | What naive folder & "\" & name gives | What JoinPath gives |
|---|---|---|---|
C:\Reports\2026 | March.csv | C:\Reports\2026\March.csv | C:\Reports\2026\March.csv |
C:\Reports\2026\ | March.csv | C:\Reports\2026\\March.csv (double separator) | C:\Reports\2026\March.csv |
/Users/anna/Reports/2026 | March.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.
| Row | A: File expected | B: Full path built by the macro | C: Result |
|---|---|---|---|
| 3 | January.csv | C:\Reports\2026\January.csv | Found |
| 4 | February.csv | C:\Reports\2026\February.csv | Found |
| 5 | March.csv | C:\Reports\2026\March.csv | Found |
| 6 | April.csv | C:\Reports\2026\April.csv | Missing |
| 7 | March.csv (trailing spaces) | C:\Reports\2026\March.csv | Found, 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 want | Formula | Example 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&"\"&A3 | double 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 |
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
- 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.Pathis empty. - Rename a sheet to
FileCheck(double-click the sheet tab). Type the folder path in B1 and the expected file names in A3 downwards. - Press
Alt+F11to open the VBA editor and choose Insert > Module. - Paste the lab code with
JoinPath,FileExistsandFolderExists, then pasteCheckExpectedFilesbelow it in the same module. KeepOption Explicitonce, at the very top. - Run
ShowPathDiagnosticsfrom the lab first (cursor inside it, thenF5). The control line must say True. If it does not, fix the environment before you go on. - Press
Ctrl+Gto 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. - Put the cursor inside
CheckExpectedFilesand pressF8repeatedly to step through it. Hover overfullPathto see the value it built on each pass. - Press
F5to run it to the end, then go back to the sheet withAlt+F11or the Excel icon and read columns B and C. - To run it from the sheet, use Developer > Macros (or
Alt+F8), pickCheckExpectedFilesand click Run. If the Developer tab is hidden, switch it on under File > Options > Customize Ribbon.
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

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 withApplication.PathSeparatoror a call toJoinPath. - 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 withDebug.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 needReplace). - Testing an unsaved workbook.
ThisWorkbook.Pathis 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
FolderExistswithGetAttr. - Wildcards in names.
Dirtreats*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
| Item | Type | What it does |
|---|---|---|
Application.PathSeparator | VBA | Returns \ on Windows and / on Mac |
ThisWorkbook.Path | VBA | Folder of the workbook that holds the code, empty until it is saved |
ThisWorkbook.FullName | VBA | Folder plus file name of that workbook |
ActiveWorkbook.Path | VBA | Folder of whichever workbook is in front, which may not be yours |
Dir(path) | VBA | Returns the file name if a matching file exists, otherwise an empty string |
Dir(path, vbDirectory) | VBA | Also matches folders, and still matches files |
GetAttr(path) | VBA | Returns the attribute bits, raises an error if the path does not exist |
Environ$("TEMP") | VBA | The user's temp folder on Windows |
Trim$(text) | VBA | Removes leading and trailing spaces from a name read from a cell |
=CELL("filename",A1) | Formula | Full path, file and sheet name of a saved workbook |
Alt+F11, F5, F8, Ctrl+G | Shortcut | VBA 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.Pathworks 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,
FileExistslets 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.PathSeparatormeans 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 CHF 9.90.
- 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
- Letting the User Choose: FileDialog