Link to home
Start Free TrialLog in
Avatar of Mirado
Mirado

asked on

Reading from a file

If I want to open a file for reading, how do I check to first be sure the file exists?
ASKER CERTIFIED SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Vbmaster
Vbmaster

Actually that FileExist function WON'T work for some files (hidden, systems etc). Here's the correct and more compact code...

   Function FileExist(strDir As String) As Boolean

      FileExist = Len(Dir("D:\A.frm", vbArchive + vbHidden + vbReadOnly + vbSystem)) > 0)

   End Function

Another solution would be to use the FileLen function like this (just another way to do it)...

   Function FileExist(Filename As String) As Boolean

      On Error GoTo Errorhandler
 
      Call FileLen(Filename)
      FileExist = True
      Exit Function

   Errorhandler:
      FileExist = False

   End Function
Actually, you have some errors in your code.  You're missing the strDir variable and you have an extra brace at the end.
The following is the correct more compact version.

Function FileExist(strDir As String) As Boolean
      FileExist = Len(Dir(strDir, vbArchive + vbHidden + vbReadOnly + vbSystem)) > 0
End Function

Avatar of Mirado

ASKER

Thanks. That did just what I needed. The first reponse would have been fine for what I was needing but thanks for the added comment too.