Does a File Exist?
 
  Back to Macro List of Topics
   
  Home
VBA has several "Working with Files" commands, one of which may be  Workbooks.Open  or a similar command. However, if the file does not exist, then your macro may crash and display an error message. To prevent this from occurring you can write a macro to first test if the file exist, then proceed as instructed. An example follows: 
 

1  Sub DoesFileExist()
2
3     dim fName,fWhatFound as String
      fName = "budget.xls"

6          fWhatFound = Dir(fName)
7
8     If fWhatFound <> "" Then
9
10        Your main code
11
12    ElseIf
13
14      MsgBox "The file" & fName &  "does not exist."
15
16    End If
17
18  End Sub
 

Comments: 

The line numbers are for reference in this article only and are not part of the code. 

Line 6   Dir(fName)  Do a  Dir  command looking for the file name in the parentheses, in this case the variable that represents  budget.xls  This command works generally the same as the DOS  Dir  command. 

Line 6 & 10  If the file is not found, nothing is placed in the variable, therefore, by testing to see the variable is not blank, you can determine the file does exist and continue with your code. 

Line 10 & 12  Your main code may be just a few lines or a very lengthy macro. Regardless, after The Main Code the  ElseIf  command is needed.

Line 14 is the code to process if the file does not exist. In this simple case, a message box is displayed. 

Line 16  To complete the  If  statement 
 

This type of macro may be useful is when copying files, searching for files on the hard drive, changing directories, and more

The  fName   in this example does not include the path. This may be necessary in your specific example.

     
Version
This macro was written and tested using Excel 97. The code is the same for all versions after Excel 5 and should run as expected, however, this code was not tested in those versions.
 
 
 
 

 

 
Top

 
 
 
 
 
 
 

 

solutions@info-stat.com