Please Note: This article is written for users of the following Microsoft Word versions: 2007, 2010, 2013, 2016, 2019, and Word in Office 365. If you are using an earlier version (Word 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Word, click here: Determining if a File Exists.
by Allen Wyatt
(last updated May 18, 2019)
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 also use the function similar to the following:
If FileThere("c:\myfile.txt") Then ' ' Do stuff here ' Else MsgBox "File Not There!" End If
WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (11831) applies to Microsoft Word 2007, 2010, 2013, 2016, 2019, and Word in Office 365. You can find a version of this tip for the older menu interface of Word here: Determining if a File Exists.
Create Custom Apps with VBA! Discover how to extend the capabilities of Office 2013 (Word, Excel, PowerPoint, Outlook, and Access) with VBA programming, using it for writing macros, automating Office applications, and creating custom applications. Check out Mastering VBA for Office 2013 today!
Many companies (and some individuals) use specific formats for naming their documents. If you want Word to recognize your ...Discover More
Backup files, created automatically by Word, have the filename extension WBK and start with the words "Backup of." If you ...Discover More
When processing non-document text files in a macro, you have a wide range of commands available for your use. One of ...Discover More
FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."
Got a version of Word that uses the ribbon interface (Word 2007 or later)? This site is for you! If you use an earlier version of Word, visit our WordTips site focusing on the menu interface.