
Tips.Net > WordTips Home > Macros > VBA Examples > Determining if a File Exists
Summary: Your macro may need to know if a particular file exists. This is easy to figure out using the Dir command, and even easier if you use it in the function provided in this tip. (This tip works with Microsoft Word 97, Word 2000, Word 2002, Word 2003, and Word 2007.)
As you are programming your macros, you may have a need to determine if a particular file exists on disk. For instance, the purpose of your macro may be to open and read from a text file. Before doing so, you will want to check to see if the file exists, in order to avoid an error.
The following function can be used to check for the existence of a file. All you need to do is pass it the full filename as a string, and the macro returns either True (if the file exists) or False (if it doesn't).
Function FileThere(FileName As String) As Boolean
FileThere = (Dir(FileName) > "")
End Function
You can use the function similar to the following:
If FileThere("c:\myfile.txt") Then
'
' Do stuff here
'
Else
MsgBox "File Not There!"
End If
Tip #819 applies to Microsoft Word versions: 97 2000 2002 2003 2007
Create and Merge! Discover how to use Word's mail merge tool to create your own custom documents. WordTips: Mail Merge Magic includes all the information you need to make your merges more productive.
Learn to use styles and you discover the real power behind Word. Fast, easy, consistent document formatting and updating is within your grasp. (more information...)
Ask a Word Question
Make a Comment
Beauty Tips
Bugs and Pests Tips
Car Tips
Cleaning Tips
College Tips
Cooking Tips
Excel2007 Tips
ExcelTips
Family Tips
Gardening Tips
Health Tips
Home Tips
Money Tips
Organizing Tips
Pet Tips
Word2007 Tips
WordTips