Excel Error 52: Fix Bad File Name or Number in VBA

VBA & macros · Updated November 3, 2026

Excel Error 52: Fix Bad File Name or Number in VBA

Excel Run-time error 52, “Bad file name or number,” usually means VBA tried to access a file using an invalid path, filename, or file number. To fix it, stop on the error, identify the failing file operation, and check the exact path and file number being supplied; the message is not an Excel worksheet-formula error.

What Excel error 52 means

Error 52 is a Visual Basic for Applications (VBA) run-time error associated with file input and output. It can appear when a macro tries to open, close, read, write, rename, delete, or check a file using a name or file handle VBA cannot use. The wording is broad: it does not, by itself, tell you whether the problem is a typo in a path, an invalid file number, or another problem with the particular file operation.

A typical example is a macro that builds a path from a folder and a filename, then passes the result to an Open statement. If the folder variable is blank, the filename contains an unintended character, or the path is assembled with a missing separator, the result may not identify the intended file. Another common source is code that uses a file number that was never assigned with FreeFile or is no longer open.

This is different from an Excel formula error such as #VALUE! or #NAME?. Editing a cell formula will not repair a VBA file-access error. The message normally comes from a macro, an add-in, or code started by a workbook event such as opening the workbook.

Find the exact VBA statement that fails

When the message appears, choose Debug if that button is available. The VBA editor highlights the statement that raised the error. Record the full statement and inspect the values used in it, especially any variables that hold a folder, filename, or file number. If you see only a general message, run the macro again from the Visual Basic Editor so you can stop closer to the failing line.

In Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor. Find the macro in the Project Explorer, place the cursor inside it, and press F8 to execute one line at a time. Hover over a variable to inspect its current value, or use the Immediate window to evaluate an expression. On a Mac, use Option+F11 where supported by the keyboard; some Mac keyboards require Fn as well. You can also open the editor from the Developer tab, if it is enabled. Excel for the web cannot run or debug VBA macros; open the workbook in the desktop app.

Look at the actual value at run time, not just the text you expect the code to create. A variable can contain a trailing space, an empty folder name, an old folder from a previous run, or a filename copied from a cell with unexpected characters. A breakpoint on the line before the file operation lets you inspect the inputs before VBA attempts to use them.

Check the path and filename

Windows paths normally include a drive or network location, folder names separated by backslashes, and a filename. For example, C:\Data\report.txt is a complete file path if that file exists in that folder. A relative path such as report.txt depends on the program’s current folder, which may not be the folder containing the workbook. That difference can make a macro work on one computer and fail on another.

  • Check for a missing folder separator when joining folder and filename values. For example, joining C:\Data and report.txt without adding a backslash can produce C:\Datareport.txt.
  • Check for blank or misspelled folder names, an unexpected extension, and leading or trailing spaces in values read from cells.
  • Make sure the code passes a file path where the statement expects a file, rather than passing a folder path alone.
  • Check that the filename is permitted by the operating system. On Windows, characters such as <, >, :, ", /, \, |, ?, and * cannot be used in an ordinary filename.
  • Confirm that the folder is available and the file is where the macro expects it to be. A moved file or unavailable network share can expose a path assumption in the code.

Be precise when interpreting nearby errors. A missing folder or file may produce a different VBA error, such as “Path not found” or “File not found,” depending on the statement and circumstances. Error 52 is not a universal label for every missing file. Use the highlighted line and the actual input values to distinguish the causes.

Use file numbers correctly

Traditional VBA file operations use a file number, written after the # symbol. Rather than hard-coding a number that may already be in use, request an available one with FreeFile, then use that same number for the matching Open, input/output, and Close operations. A file number is not the filename: the path identifies the file, while the number identifies the open file connection within VBA.

For example, a program that opens a file using one number and later tries to read from another can fail. So can code that closes a file and then tries to read from its old file number. Review each branch of the macro: if an error handler or conditional branch closes the file early, later code must not assume it remains open. Pair each successful Open with an appropriate Close, including when the macro exits early.

Also check that the operation matches the file’s intended use. VBA’s Open statement has modes such as Input, Output, and Append; they are not interchangeable. For instance, use Input to read an existing text file, while Output creates a file for writing and can replace existing contents. Choosing a different mode is not a safe workaround for an invalid path, and a writing operation can change data.

Test a path safely with a small example

The following example checks for a particular text file, obtains an available file number, opens the file for input, and closes it. Change the example path to a real file on your computer. It does not write to the file. The error handler reports the VBA error rather than silently treating every failure as a missing file.

Sub CheckTextFile()
    Dim fullPath As String
    Dim fileNo As Integer
    Dim opened As Boolean
    Dim errorNumber As Long
    Dim errorText As String

    ' Replace this Windows example with an existing text file.
    fullPath = "C:\Data\report.txt"

    If Len(Dir$(fullPath)) = 0 Then
        MsgBox "The file was not found at: " & fullPath, vbExclamation
        Exit Sub
    End If

    On Error GoTo FileError
    fileNo = FreeFile
    Open fullPath For Input As #fileNo
    opened = True
    Close #fileNo
    opened = False
    MsgBox "The file opened and closed successfully.", vbInformation
    Exit Sub

FileError:
    errorNumber = Err.Number
    errorText = Err.Description
    On Error Resume Next
    If opened Then Close #fileNo
    On Error GoTo 0
    MsgBox "Error " & errorNumber & ": " & errorText, vbExclamation
End Sub

This is a diagnostic example, not a complete import routine: it confirms that VBA can open the selected file but does not read its contents. The Dir$ check is useful for a normal file path, but it does not prove that every later operation will succeed. The file could change between the check and the open, or the macro could lack access. If you adapt the code, retain error handling around the operation itself. Save a copy of the workbook before running any macro you modify; VBA actions cannot be undone with Ctrl+Z.

Consider permissions, network folders, and cloud files

A path can look correct and still be unavailable to the macro. The account running Excel may not have permission to read or write the target folder. A mapped network drive may be connected under a different sign-in, or a VPN or network connection may be unavailable. Check access in File Explorer using the same Windows account and confirm that the intended file can be opened there.

For OneDrive or SharePoint files, distinguish a local synchronized path from a web address. VBA file statements generally operate on file-system paths; pasting a browser URL into an Open statement does not turn it into a local file path. If the organization’s synchronization client has made the file available locally, use its actual local path and confirm that the file is downloaded and accessible. Organizational access rules may also restrict a macro even when a user can view a document in a browser.

Do not treat a permission problem as a reason to disable security controls or run Excel as an administrator without a clear need. First verify the intended location and ask the folder owner or IT support about access. Error 52 describes a failed file operation; it does not establish that the workbook is safe or that the requested access should be granted.

Why the error can appear only on one computer

Macros often contain assumptions that hold on the author’s computer but not elsewhere: a personal folder name, a particular drive letter, a file saved to the desktop, or a mapped network location. Windows usernames and folder layouts differ. A workbook copied to another machine may therefore assemble a path that points nowhere or to a location the user cannot access.

A more portable macro can ask the user to choose a file or build a path from a known workbook location, rather than hard-coding one person’s folders. If a workbook-relative path is used, verify that the related file is actually stored alongside the workbook or in the expected subfolder. This can still fail when the workbook has not been saved, has been moved, or is opened from a location with different access rules, so validate the result before opening the file.

Mac Excel also uses different folder conventions from Windows. A Windows path beginning with a drive letter, such as C:\Data\report.txt, will not identify the corresponding Mac file. Mac paths commonly use POSIX-style locations, and the exact path must match the Mac’s folders and permissions. Excel for Mac supports VBA, but operating-system file paths and some dialogs differ. Excel for the web does not run VBA, so a macro-based remedy requires desktop Excel.

Prevent error 52 in future macros

Reliable file-handling code validates inputs and handles failure at the point where it occurs. Avoid suppressing errors broadly with On Error Resume Next; it can hide the line that failed and allow a macro to continue with incomplete data. If you use it for a narrowly defined cleanup action, restore normal error handling immediately afterward and report unexpected failures clearly.

  • Build paths from clearly named variables and inspect the final path before opening or changing a file.
  • Use FreeFile for file numbers and keep open/read/write/close operations paired.
  • Check that required folders and files exist, but still handle errors from the actual operation.
  • Test with a copy of representative files and with the same permissions and folder layout users will have.
  • Tell users which path failed and which operation was attempted, without displaying sensitive file contents.

If the error occurs in a workbook you did not create, identify whether an add-in, a startup macro, or a workbook event is responsible before changing code. If the file is from an untrusted source, do not enable macros merely to investigate. Ask the sender or your organization’s support team to verify the file and explain the macro’s purpose.

Frequently Asked Questions

Is Excel error 52 caused by a formula?
No. Run-time error 52 is associated with VBA file operations, not ordinary worksheet formulas. A macro or add-in may be running even if you were working in a worksheet when the message appeared.

What does “Bad file name or number” mean in VBA?
It means VBA could not use a filename, path, or file number in the file operation it attempted. Debug the macro and inspect the highlighted statement and the values it uses to identify the specific cause.

Can a missing file cause error 52?
A missing file can cause a file operation to fail, but VBA may report another error depending on the statement and situation. Check both the path and the exact error rather than assuming every missing file produces error 52.

Why does the macro work on my computer but not someone else’s?
The code may rely on your username, drive letter, local folder, network mapping, or permissions. Compare the complete path used on each computer and confirm that the other user can access the target location.

Can Excel for the web fix or run a VBA macro?
No. Excel for the web does not run VBA macros. Open the workbook in desktop Excel to debug or run its VBA code; the path and file-access details must still be valid for that computer.

Should I use “On Error Resume Next” to get past error 52?
Not as a general fix. It can conceal the failed operation and leave the macro working with missing or incorrect data. Correct the path or file number, and use targeted error handling that reports the failure.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.