【VBA】Check if file exists

You can check if file exists!

PR

VBA Code

As an example, check if “hogehoge.txt” exists.

hogehoge.txt
hogehoge.txt
Option Explicit

Sub sampleProc()
    
    Dim fso As Object
    Dim filePath As String
    
    'Set "File path you want to check"
    filePath = "C:\Users\user\Desktop\hogehoge.txt"
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    'Check if file exists
    If fso.FileExists(filePath) Then
        MsgBox "The file is exists."
    Else
        MsgBox "The file is not exists."
    End If
    
    Set fso = Nothing
    
End Sub

Set “File path you want to check”(Line 9).

Check if file exists(Line 14~18).

PR

Result

You checked if file exists!

Result
Result
PR

FYI No.1

Also, you can check if folder exists!

For more information, see the following article:


PR

FYI No.2

For more information about following, see the following official online manual:

FileExists method” of “FileSystemObject”

タイトルとURLをコピーしました