Windows has a 256 characters limit for file paths, but users can definitely create files with path longer than 256 characters. Let's call file paths shorter than or equal 255 characters as short paths, and those longer than or equal to 256 characters as long path.
While working on another problem, I need to check whether a file exists given its file path, regardless of the length of the file path, regardless of normal paths or UNC paths on Windows. Is it possible with VBA?
What I have tried
In VBA, there are two main ways to check file existence:
- Use
Dir()
.
Dim isExists As Boolean
isExists = Dir("some\file\path") = vbNullString
- Use
FileSystemObject
(FSO).
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim isExists As Boolean
isExists = objFSO.FileExists("some\file\path")
Dir()
is not useful here because:
- It does not support file paths with Unicode characters, e.g. Chinese characters. And there are Chinese characters in the file paths that I work with.
- For long paths, it throws File Not Found error no matter the file exists or not.
FileSystemObject
, on the other hand, supports file paths with Unicode characters, but I cannot get it to report file existence correctly for files with a long path.
Whenever a long path is given, objFSO.FileExists(...)
returns False
even when the file obviously exists in Windows File Explorer?!
For example,
' Short paths: `True` if file exists and `False` otherwise, as expected.
objFSO.FileExists("C:\some\short\path") ' Windows native path.
objFSO.FileExists("\\server\drive\some\short\path") ' UNC path.
' Long paths: `False` no matter the file exists or not, unfortunately.
objFSO.FileExists("C:\some\very\long\path\that\may\have\unicode\characters") ' Windows native path.
objFSO.FileExists("\\server\drive\some\very\long\path\that\may\have\unicode\characters") ' UNC path.
I have read the Microsoft VBA documentation many times, e.g. FileExists method, but with no luck.
Please forgive me to insert a small rant here that nowhere in the documentation of Dir()
mentions the fact that it does not support Unicode characters. Come on!
What I expect
Can anyone please point out what I may have missed, or answer the question whether this is solvable with VBA? If so, what can I do? It will be kind of you if you include some code examples to illustrate your answer. Thank you!