2017年6月3日

【Excel】ファイルの存在確認をするマクロ


ファイルの存在を確認するには、Dir関数を使った方法とFileSystemObjectを使った方法があります。

Dir関数

Dir関数はファイルが存在するとパスを含まないファイル名だけを返します。また、ファイルが存在しない場合には空文字("")を返します。
1
2
3
4
5
6
7
8
9
10
11
12
13
Sub CheckFile1()
 
    Dim filePath As String
     
    filePath = "C:\work\Excel\output.txt"
     
    If Dir(filePath) <> "" Then
        MsgBox filePath & " は存在します。"
    Else
        MsgBox filePath & " は存在しません。"
    End If
     
End Sub


FileSystemObject

FileSystemObjectのFileExistsメソッドでファイルの存在確認が出来ます。
FileExistsメソッドは、対象のファイルが存在する場合には「True」を返します。

ただ、このFileSystemObjectを使うには、あらかじめ参照設定で、「Microsoft Scripting Runtime」にチェックを入れておく必要がありますので注意が必要です。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
Sub CheckFile2()
 
    Dim fso As New FileSystemObject
    Dim filePath As String
     
    filePath = "C:\work\Excel\output.txt"
     
    If fso.FileExists(filePath) = True Then
        MsgBox filePath & " は存在します。"
    Else
        MsgBox filePath & " は存在しません。"
    End If
     
End Sub





スポンサーリンク



Follow Me on Pinterest
Clip to Evernote