|
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()
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. 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 |