Test if folder exists prior to creating it - VBA

I

Isissoft

I am trying to output a file from Access - I use the following code to make
a folder if it does not already exist;
DestFile2="C:\Copy"
If Dir(DestFile2) = " " Then ' CHECK IF PATH EXISTS
MkDir (DestFile2) ' If NOT - Make IT
End If ' End Check Folder Name

This does work if the folder does not exist, but fails if it does already -
obviously my test is wrong ?

Can anyone give me the code to do this ?

I have a function that will do the job but I would like to sort this
problem for other reasons.

Thanks for any help.
 
B

boblarson

I think the part that you are having trouble with is that you have a space
between your double quotes and not together:
DestFile2="C:\Copy"
If Dir(DestFile2) = " " Then

should be
DestFile2="C:\Copy"
If Dir(DestFile2) = "" Then


--
Bob Larson
Access MVP
Access World Forums Administrator
Utter Access VIP

Tutorials at http://www.btabdevelopment.com

__________________________________
 
A

Arvin Meyer [MVP]

Branching the code and/or error handling should work for you:

DestFile2="C:\Copy"
If Dir(DestFile2) = " " Then ' CHECK IF PATH EXISTS
MkDir (DestFile2) ' If NOT - Make IT
Else
Exit Sub
End If ' End Check Folder Name
 
D

Douglas J. Steele

Both Bob and Arvin seem to have forgotten to include the vbDirectory option
for the Dir function call:

DestFile2="C:\Copy"
If Len(Dir(DestFile2, vbDirectory)) = 0 Then ' CHECK IF PATH
EXISTS
MkDir (DestFile2) ' If NOT - Make IT
End If ' End Check Folder Name
 
A

Arvin Meyer [MVP]

Yep, I just copied code he stated was working without looking further.
Actually in my own code I use:

If Not DirExists("C\Copy") Then
MkDir("C\Copy")
End If

Public Function DirExists(strDirectory As String) As Boolean
DirExists = (Dir(strDirectory, vbDirectory) <> "")
End Function
 

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