How determine if directory exists

  • Thread starter Thread starter windsurferLA
  • Start date Start date
W

windsurferLA

I know this question has been asked before, but post has expired.

I want to find out if a certain directory exists, and if not to make it.
I know you can use if Dir$(file.xls)<>"" to detect files.
I know I can use MkDir to make the directory if it doesn't exist.

My problem is I don't want to trigger error with MkDir if the directory
already exists.

How do I test to determine if a specific directory exists?
 
Dir() takes a second argument:

If Dir("C:\Stuff", vbDirectory) = "" then
'create folder
End If

Tim
 
This function should do the job:

Function FolderExists(PathName As String) As Boolean
On Error Resume Next
If Len(PathName) > 0 Then
FolderExists = ((GetAttr(PathName) And vbDirectory) > 0)
Err.Clear
End If
End Function


RBS
 
You can use a function like

Function DirExists(PathName As String) As Boolean
If Dir(PathName, vbDirectory) = vbNullString Then
DirExists = False
Else
DirExists = True
End If
End Function

However, with this code if you pass in a filename (e.g., "C:\Test\Temp.txt")
the function will return True. If you want to ensure that PathName is really
a directory and not a file, use

Function DirExists(PathName As String) As Boolean
If Dir(PathName, vbDirectory) = vbNullString Then
DirExists = False
Else
If Dir(PathName, vbNormal) = vbNullString Then
DirExists = True
Else
DirExists = False
End If
End If
End Function

This will return True only if PathName is the name of an existing directory.
If PathName is a non-existent directory or the name of an existing file, it
will return False.


--
Cordially,
Chip Pearson
Microsoft MVP - Excel, 10 Years
Pearson Software Consulting
www.cpearson.com
(email on the web site)
 
Thanks for prompt reply... I expect to use your suggestion in
combination with Chip Peason's expansion to preclude the possibility of
a file location being interpreted as a directory.

WindsurferLA
 
Thanks for prompt reply. Your approach would work, but I expect to use
that suggested by Chip Pearson because it precludes inadvertently
thinking that the path name to a file is a directory.
 
Thank you for your prompt reply and fine solution to my problem.
Furthermore, your reply prompted me to look up and learn about
vbNullString, vbDirectory, and vbNormal attributes that I had not
previously encountered or used.

WindsurferLA
 
Back
Top