「Excel VBA」dirメソッドでファイルがあるか存在確認するサンプル

2022年1月13日

環境
Windows 10 64bit
Excel 2013
書式
dir(フォルダ名 & ファイル名)
dirでファイルの存在確認ができます。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Sub funcA()
Dim fdName As String
Dim fileName As String
'フォルダ変数名
fdName = "c:\test10\"
'ファイル変数名
fileName = "test1.xlsx"
'dirでファイルの存在確認
If Dir(fdName & fileName) = "" Then
MsgBox "ファイルが存在しません"
End If
End Sub
Sub funcA() Dim fdName As String Dim fileName As String 'フォルダ変数名 fdName = "c:\test10\" 'ファイル変数名 fileName = "test1.xlsx" 'dirでファイルの存在確認 If Dir(fdName & fileName) = "" Then MsgBox "ファイルが存在しません" End If End Sub
Sub funcA()

    Dim fdName As String
    Dim fileName As String
    'フォルダ変数名
    fdName = "c:\test10\"
    'ファイル変数名
    fileName = "test1.xlsx"
    
    'dirでファイルの存在確認
    If Dir(fdName & fileName) = "" Then
        MsgBox "ファイルが存在しません"
    End If
    
End Sub

実行結果
「ファイルが存在しません」ダイアログが表示されます

Excel VBA

Posted by arkgame