Fandom

Visual Basic Wiki

How to check if a file exists

66pages on
this wiki
Add New Page
Talk0 Share

If you insert the following line before the spot where you intend to use the file, it will raise a ‘File not found’ error if the file doesn't exist:

FileLen <file name>

Substitute <file name> with a string constant or variable specifying the file name. If you prefer to use a more robust check that does not generate an error, just add this function to your project:

Public Function FileExists(filename As String) As Boolean
    FileExists = Len(Dir(filename, vbNormal)) > 0
End Function

Then call it as expected to check if a file exists:

If FileExists("C:\test.bas") Then
   <do whatever to the file here>
End If

Alternatively, you can use the FileSystemObject to check for a file's existence:

Public Function FileExists(filename As String) As Boolean
    Static fso As Object
    If fso Is Nothing Then Set fso = CreateObject("Scripting.FileSystemObject")
    FileExists = fso.FileExists(filename)
End Function

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.