How determine if directory exists

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?
 
T

Tim Williams

Dir() takes a second argument:

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

Tim
 
R

RB Smissaert

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
 
C

Chip Pearson

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)
 
W

windsurferLA

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
 
W

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.
 
W

windsurferLA

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top