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 VBA 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
This function works by using the Dir function, which checks for a file in a directory. If the file exists, then Dir returns the full path of the file. The True/False condition of the function is derived by comparing what Dir returns against an empty string. If something is returned, the file exists because Dir doesn't return an empty string.
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
Note:
ExcelTips is your source for cost-effective Microsoft Excel training. This tip (2516) applies to Microsoft Excel 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Excel (Excel 2007 and later) here: Determining If a File Exists.
Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!
When you save your workbooks, Excel can also save a preview image (thumbnail) that can be displayed in the Open dialog ...
Discover MoreDoes your macro need to add information to the end of a text file? This is called appending, and is done using the ...
Discover MoreThe Personal.xls workbook is used primarily to store macros that you want available through all of your workbooks. ...
Discover MoreFREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
2018-11-19 06:10:59
Hello Dave,
Yes, as far as I know you’re right. – I have only seen it in the practice return a simple name. I don’t think there is any way to make it return a full path.
Actually what Dir seems to do is “return the thing it finds “There”” , where “There” is like in Dir(“There”). In other words what is at the Path you give it.
If you give it the full path and file name, as Allen Wyatt is suggesting, then all it can give you back is that one thing if it is there, which is your file. In other words, the only thing it finds at your file is your file
( I think Dir is a throw back to old computer stuff. I seem to remember that you typed Dir and something.. and then you got it back, or the path changed to it.. or something similar to that happened.. I don’t quite remember what… it was a long time ago..)
If Instead of giving Dir the full path and file name, I give it the full path like this,.._
Dir(ThisWorkbook.Path & "\")
Or this
Dir(“c:\”)
_.. , then it will return me any file from that path. (It will return the first file there, or maybe it goes by alphabetical order - I am not sure how it organises the order)
By the way, I just took a look at the documentation and I see that Dir( ) has a second argument. As Allen Wyatt is not using that, then it defaults to vbNormal , like this in my last example:
Dir(ThisWorkbook.Path & "\", vbNormal)
Dir(“c:\”, vbNormal)
If I do it slightly differently like these .._
Dir(ThisWorkbook.Path & "\", vbDirectory)
Dir(“c:\”, vbDirectory)
_.. then folders are also included in what it looks for
_.___________________________
In VBA I see Dir a lot in looping through files in a folder. That works nicely because of 2 characteristics of the VBA Dir
_1 The Dir takes a wild card in the first string argument in ( ) and returns initially the first thing that it finds that matches that search criteria.
_2 If you use just Dir on its own without the ( ) then it returns the next thing it finds that matches the last used search criteria
This code is like to find all Excel files
Sub Duh_XL()
Dim MeFiles As String, MeStrungOut As String
Let MeNextFile = Dir(ThisWorkbook.Path & "\*.xls*", vbNormal) ' Search criteria is all Excel files in the same folder as the workboook that this code is in
Do While MeNextFile <> "" '======
Let MeStrungOut = MeStrungOut & MeNextFile & vbCrLf
Let MeNextFile = Dir ' use of just Dir looks for next file which meets the last search criteria
Loop 'if MeNextFile <> "" '======
MsgBox prompt:="The found files were:" & vbCrLf & MeStrungOut: Debug.Print "The found files were:" & vbCrLf & MeStrungOut ' From XL Spreadsheet, Hit Alt+F11 to get in VB Editor. From in VB Editor hit Ctrl+g to get immediate window to see the Debug.Print ed stuff
End Sub
As far as I can tell, if you use this instead , in that last code, .._
MeNextFile = Dir(ThisWorkbook.Path & "\", vbDirectory)
_.. , then you get a complete list of everything there at the path
ThisWorkbook.Path & "\"
That includes Files , Folders and maybe other strange things .. .
Alan Elston
2018-11-18 13:29:22
Dave
Good tip - however, maybe a slight correction: "If the file exists, then Dir returns the full path of the file". Not so, Dir only returns the filename, eg, Dir("C:\myPath\myFile.txt") returns "myFile.txt".
2015-03-27 14:23:06
Franklyn
Thank you, it works great.
2014-07-15 17:28:42
Greg Yoder
Never mind I figured it out. Had to add the function to the end of my sub
2014-07-15 17:22:01
Greg Yoder
I am using Excel 2010. Writing a macro to load a file from c:temp.
When I try using FileThere I get the following Error.
Compile Error SubFunction not defined?
Got a version of Excel that uses the menu interface (Excel 97, Excel 2000, Excel 2002, or Excel 2003)? This site is for you! If you use a later version of Excel, visit our ExcelTips site focusing on the ribbon interface.
FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
Copyright © 2021 Sharon Parq Associates, Inc.
Comments