Checking if a file exists.
Checking if a file exists.
(OP)
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
Sub test()
If Dir("c:\X\ProjsB") = "" Then
MkDir "c:\X\ProjsB"
End If
End Sub





RE: Checking if a file exists.
--
www.bridgeart.net
RE: Checking if a file exists.
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
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
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
Hope this helps. If I misunderstood something, post back.
Regards,
Mike
RE: Checking if a file exists.
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
RE: Checking if a file exists.
CODE
If FSO.FileExists(FileSpec) Then ...
Regards,
Mike