Error 52, “Bad file name or number”, covers two faults that share one message: a file name the system will not accept (empty, containing illegal characters, or an invalid path form), and a file number used with statements like Print # or Close that does not refer to an open file. Both are code bugs, usually in how a name is built from data or how a file number is tracked.
\ / : * ? " < > |) and trim trailing spaces and dots before composing the path:Function SafeName(s As String) As String
Dim bad As Variant, i As Long
bad = Array("\", "/", ":", "*", "?", Chr$(34), "<", ">", "|")
For i = LBound(bad) To UBound(bad)
s = Replace(s, CStr(bad(i)), "-")
Next i
SafeName = Trim$(s)
End Function
Dim fn As Integer: fn = FreeFile guarantees the number is genuinely free, and every later statement should use that variable.If names are legal and numbers come from FreeFile, check whether the path is being interpreted differently than expected: a relative path resolves against the application's current directory, which other code (or a common dialog) may have changed. Print the full resolved path at the point of failure.
Which characters are illegal in a Windows file name? Backslash, slash, colon, asterisk, question mark, double quote, angle brackets, and vertical bar cannot appear in a file name. A name built from data containing any of them raises error 52 when used.
What does the “number” half of error 52 mean? VBA file statements refer to open files by number. Using a number that was never opened, or was already closed, is a bad file number and raises the same error 52.