tiredofit
Well-known Member
- Joined
- Apr 11, 2013
- Messages
- 1,924
- Office Version
- 365
- 2019
- Platform
- Windows
The following code to check if a file or folder exists is taken from here:
This checks for a file:
whereas this checks for a folder:
The problem I'm getting is if I pass a string such as:
into the Sub Test_File_Exist_With_Dir, it still returns true, even though I've only passed in a folder location and not the name of a file.
How can I amend this?
Thanks
(although using the FSO method does work).
Rich (BB code):
This checks for a file:
Rich (BB code):
Sub Test_File_Exist_With_Dir()
Dim FilePath As String
Dim TestStr As String
FilePath = "C:\Users\Ron\test\book1.xlsm"
TestStr = ""
On Error Resume Next
TestStr = Dir(FilePath)
On Error GoTo 0
If TestStr = "" Then
MsgBox "File doesn't exist"
Else
MsgBox "File exist"
End If
End Sub
whereas this checks for a folder:
Rich (BB code):
Sub Test_Folder_Exist_With_Dir()
Dim FolderPath As String
FolderPath = "C:\Users\Ron\test"
If Right(FolderPath, 1) <> "\" Then
FolderPath = FolderPath & "\"
End If
If Dir(FolderPath, vbDirectory) <> vbNullString Then
MsgBox "Folder exist"
Else
MsgBox "Folder doesn't exist"
End If
End Sub
The problem I'm getting is if I pass a string such as:
Rich (BB code):
"C:\Users\Ron\test"
into the Sub Test_File_Exist_With_Dir, it still returns true, even though I've only passed in a folder location and not the name of a file.
How can I amend this?
Thanks
(although using the FSO method does work).
Last edited: