Hi
Code to check whether file exists
Option Explicit
Public Function FileExists(Path As String) As Boolean
If Dir(Path) <> "" Then
FileExists = True
Else
FileExists = False
End If
End Function
Sub TestFileExists()
Dim myFile As String
myFile = "c:\folder\file.ext"
If FileExists(myFile) = True Then
'Your code here
Else
'Your code here
MsgBox "The file does not exist", vbCritical
End If
End Sub
U could use the above 2 methods to check if a file exists. Its much
simpler this way since u do not need to call the scripting fso object.
Just use the dir method.
-------------------------------------------------
DIR Method Defination from VBA Help:
Returns a String representing the name of a file, directory, or folder
that matches a specified pattern or file attribute, or the volume label
of a drive.
Syntax
Dir[(pathname[, attributes])]
The Dir function syntax has these parts:
-------------------------------------------------
Now, for ur request to check the existence of a particular directory, u
could use the two methods below, either DirExists or DirExists2. The
first method is quite clean, just use the inbuilt methods to check if
the directory exists.
The 2nd method is equally good and simplified because it just uses the
length function to determine if the return of the directory function
where u pass the folder is empty or not. Both is equally sufficent I
guessed, choose the one you prefer.
Function DirExists(strDir As String) As Boolean
Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
DirExists = oFSO.FolderExists(strDir)
Set oFSO = Nothing
End Function
Function DirExists2(strDir As String) As Boolean
If Len(Dir(strDir, vbDirectory)) = 0 Then
DirExists2 = False
Else
DirExists2 = True
End If
End Function
Sub TestDirExists()
Dim myDir As String
myDir = "c:\folder"
If DirExists1(myDir) Then
'Your Code here
Else
'Your Code here
MsgBox "The dir does not exist", vbCritical
End If
End Sub
Kudos!