【ExcelVBA】ファイルの存在確認

ExcelVBA,ファイルの操作

ファイルの存在確認

CreateObject関数で確認

Sub Sample()

  Dim FilePath As String
  Dim FS As Object
  
  Set FS = CreateObject("Scripting.FileSystemObject")
  
  FilePath = "C:\test.txt"
  
  If FS.FileExists(FilePath) Then
    MsgBox "ファイルあるよ!"
  Else
    MsgBox "ファイルないよ!"
  End If

  Set FS = Nothing

End Sub

10行目の FileExists メソッドは、複数のファイルを指定するための "*" (アスタリスク) および "?" (疑問符) のワイルドカード文字は使用できません。

Dir関数で確認

Sub Sample()

  Dim FilePath As String
  
  FilePath = "C:\te*.txt"
  
  If Dir(FilePath) <> "" Then
    MsgBox "ファイルあるよ!"
  Else
    MsgBox "ファイルないよ!"
  End If

End Sub

7行目の DIR関数 は、Windowsの場合、複数のファイルを指定するための "*" (アスタリスク) および "?" (疑問符) のワイルドカード文字を使用できます。