Here is a handy little tip (and function) for all you Visual Basic developers out there. I use this quite often, it’s useful to see if whatever file you are working with or looking for exists before you start trying to access it. So, here we have a nice little function you can drop into a module and call from anywhere when you need it.
(Need to do the same for a directory? That function is here!)
Check it out:
Public Function fFileExists(ByVal FileName As String) As Boolean
Dim TempAttr As Integer
On Error GoTo ErrorFileExist
TempAttr = GetAttr(FileName)
fFileExists = ((TempAttr And vbDirectory) = 0)
GoTo ExitFileExist
ErrorFileExist:
fFileExists = False
Resume ExitFileExist
ExitFileExist:
On Error GoTo 0
End Function
There you have it! Just call it in an IF statement like so:
if fFileExists("c:\temp\myfile.txt") then
' Hey, it's there
else
' Nope, no file here
end if
It’s just that easy, enjoy!
Pingback: See If A Directory Exists In Visual Basic | Solarum - Information For Everyone