bottom
Great WordTips!
         
Your e-mail address is safe!
Close Note

Tips.Net > WordTips Home > Macros > VBA Examples > Determining if a File Exists

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


Step Up and Take Control! Subscribers to WordTips know just how valuable a resource it is. WordTips Premium provides twice the number of exceptional, easy-to-understand tips every week in an ad-free newsletter, as well as substantial discounts on WordTips archives and e-books.
 
Check out WordTips Premium today!

Helpful Links

Ask a Word Question
Make a Comment

Tips.Net Home
Tips.Net Store

WordTips FAQ
WordTips Premium

Learn Access Now

Beauty Tips
Car Tips
Cleaning Tips
College Tips
Cooking Tips
Excel2007 Tips
ExcelTips
Family Tips
Gardening Tips
Health Tips
Home Tips
Money Tips
Organizing Tips
Pest Tips
Pet Tips
Word2007 Tips
WordTips

Advertise on the
WordTips Site

 

Great Info!

Get tips like this every week in WordTips, a free productivity newsletter. Enter your e-mail address and click "Subscribe."
     
(Your e-mail address will never be shared with anyone, ever.)