Check if file exists


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'**********************************************************************************************************
' Name:                 fileExists
' Author:               mielk | 2012-12-02
'
' Comment:              Function to check if file with the given filepath exists in the file system.
'                       This is a wrapping function for method .fileExists of FileSystemObject class that
'                       lets a user avoid declaring a new instance of FileSystemObject class when invoking
'                       this function.
'
' Parameters:
'   folderPath          The path of a file to be checked.
'
'
' Returns:
'   Boolean             True - if file with the given filepath exists.
'                       False - otherwise.
'
'
' --- Changes log -----------------------------------------------------------------------------------------
' 2012-12-02        mielk           Function created.
'**********************************************************************************************************

Public Function fileExists(filepath As String) As Boolean
    Const METHOD_NAME As String = "fileExists"
    '------------------------------------------------------------------------------------------------------
    Static objFSO As Object         '(Late binding that allows to use the function, even if
                                    'Microsoft Scripting Runtime library is not loaded)
    '------------------------------------------------------------------------------------------------------


    'Create FileSystemObject instance if it hasn't been created yet. ------------------------------------|
    If objFSO Is Nothing Then                                                                           '|
        Set objFSO = VBA.CreateObject("Scripting.FileSystemObject")                                     '|
    End If                                                                                              '|
    '----------------------------------------------------------------------------------------------------|


    fileExists = objFSO.fileExists(filepath)


End Function