Loading

Monday, March 9, 2009

Determining Whether A File Exists Or Not

There are several ways to check whether a file exists. By using Microsoft Excel VBA statements and functions, or by using FileSystemObject (Microsoft Scripting Library). The following function returns True if a particular file exist, and return False if file does'nt exist. This function uses Dir function to check whether a file exists or not.

Function isFileExist(ByVal fname As String) As Boolean
isFileExist = False
If Dir(fname) <> "" Then isFileExist = True
End Function

Here's example how to use the function above:

Sub FunctionTest()
If isFileExist("D:\SomeFile.txt") = False Then
MsgBox "File not exists."
Else
MsgBox "File already exist."
End If
End Sub

The next function do exactly as previous function, but this function uses FileSystemObject to check whether a file exist:

Function isFileExist2(ByVal fname As String) As Boolean
    Set fs = CreateObject("Scripting.FileSystemObject")
    
    isFileExist2 = fs.FileExists(fname)
End Function
FIN.

SHARE TWEET

Thank you for reading this article Determining Whether A File Exists Or Not With URL https://x-tutorials.blogspot.com/2009/03/determining-whether-file-exists-or-not.html. Also a time to read the other articles.

0 comments:

Write your comment for this article Determining Whether A File Exists Or Not above!