ray88’s diary

お仕事で困ったとき用の自分用の覚書

VBA ファイルの存在確認(FileSystemObject)

■呼び出し元プロシージャ

Sub test()
    Dim filePath As String
    Dim Result As Boolean
    filePath = "C:\Users\cryst\OneDrive\デスクトップ\テスト\テストフォルダ\テスト.xlsx"
    If IsExistsFile(filePath) Then
        MsgBox "ファイルは存在します"
    Else
        MsgBox "ファイルは存在しません"
    End If
End Sub

■ファンクションプロシージャ

Function IsExistsFile(targetPath As String) As Boolean
'----------------------------------------------------
'機能:指定されたファイルパスが存在するか確認し
'   結果をTrueまたはFalseで返す
'引数1:ファイルパス
'-----------------------------------------------------
     With CreateObject("Scripting.FileSystemObject")
        If .FileExists(targetPath) Then
            IsExistsFile = True
        Else
            IsExistsFile = False
        End If
    End With
End Function

ray88.hatenablog.com