Microsoft Office Tutorials and References
In Depth Information
Checking Whether or Not a File Exists
Checking Whether or Not a File Exists
This macro demonstrates how to check if a file exists in a path.
Example file:
E008.xls
Scenario: When running a macro, it may be necessary to
access different files stored in the user's computer. However,
if one of those files is missing, the macro is likely to fail. This
example shows how to check if a file exists in order to
display an error message and cancel or exit the macro in a
user-friendly manner.
Exl
View the Appendix to learn how to store this procedure
in a Standard module.
Option Explicit¶
' * * * * *¶
Function FileExists(sFullName As String) As Boolean¶
FileExists = Len(Dir(PathName:=sFullName)) > 0¶
End Function¶
' * * * * *¶
Sub TestFileExists()¶
'Variable Declaration¶
'Variable for search path¶
Dim Path As String¶
'Variable to test existence¶
Dim Exists As Boolean¶
'Change the following variables¶
'Set variable via hard coding¶
'Path = "C:\My file.txt"¶
'Set variable via user input¶
Path = Range("B1").Value¶
Exists = FileExists(Path)¶
If Exists Then¶
MsgBox "The file exists"¶
Else¶
MsgBox "The file doesn't exist"¶
End If¶
End Sub¶
 
Search JabSto ::




Custom Search