Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations waross on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking if a file exists.

Status
Not open for further replies.

mtroche

Civil/Environmental
Jun 4, 2001
39
0
0
PR
I have this SUB to look if a file exists. If the file exists it's supposed to do nothing, but if it doesn't exists the file is created. The problem is that if the file already exists the following error occurs: "Path not found." Of course, the file "X" does exists in "c:\".

Sub test()
If Dir("c:\X\ProjsB") = "" Then
MkDir "c:\X\ProjsB"
End If
End Sub
 
Replies continue below

Recommended for you

mtroche,

I'm assuming you mean folders (directories) not files. Your code works for me if the path c:\X already exists (and the optional attributes parameter of the Dir function is set to vbDirectory). Otherwise, the MkDir call throws the "Path not found" error. In other words, MkDir can only create a directory one level down from an existing directory. It cannot create all the missing subdirectories in the path parameter in one go.

If c:\X doesn't exist, then this works:
Code:
Sub test()
    If Dir("c:\X\ProjsB", vbDirectory) = "" Then
        MkDir "c:\X"
        MkDir "c:\X\ProjsB"
    End If
End Sub

Instead of using the VBA Dir & MkDir commands, I recommend using the FileSystemObject for file & folder manipulations. Here is a generalized function that will create a path an arbitrary number of levels deep. It returns True or False indicating success or not.
Code:
Function CreateFilePath(ByVal FPath As String) As Boolean
Dim FSO As FileSystemObject
Dim ParsedPath As Variant
Dim TempPath As String
Dim i As Long

   On Error Resume Next
   Set FSO = New FileSystemObject
   ParsedPath = Split(FPath, "\")
   TempPath = ParsedPath(0)
   For i = 1 To UBound(ParsedPath)
     TempPath = TempPath & "\" & ParsedPath(i)
     FSO.CreateFolder (TempPath)
   Next i
   CreateFilePath = FSO.FolderExists(FPath)
   Set FSO = Nothing
   
End Function
This function requires that a reference to the Microsoft Scripting Runtime be set.

Hope this helps. If I misunderstood something, post back.

Regards,
Mike
 
I once found this bit of code to establish if a file exists and have used it ever since.


Function FileExists%(filename$)

Dim f%
'trap any errors that may occur
On Error Resume Next
'get a free file handle
f% = FreeFile
Open filename$ For Input As #f%
Close #f%
FileExists% = Not (Err <> 0)

End Function
 
Staying on the FileSystemObject bandwagon, the following will determine if a file exists:
Code:
Set FSO = New FileSystemOBject
If FSO.FileExists(FileSpec) Then ...
where FileSpec is the path + filename you are checking.


Regards,
Mike
 
Status
Not open for further replies.
Back
Top