<目次>
(1) VBAでファイルやフォルダの存在チェックを行う方法
(1-1) 構文
(1-2) サンプルプログラム
(1) VBAでファイルやフォルダの存在チェックを行う方法
(1-1) 構文
●ファイルの存在チェック
CreateObjectファンクションで「FileSystemObject」オブジェクトを生成して、そのFileExistsメソッドを使います。FileExistsメソッドの引数には存在チェック対象のファイルパスを与えます。
(構文)
- CreateObject("Scripting.FileSystemObject").FileExists(CheckPath)
- Function IsFile(ByVal CheckPath As String) As Boolean
- IsFile = CreateObject("Scripting.FileSystemObject").FileExists(CheckPath)
- End Function
●フォルダの存在チェック
CreateObjectファンクションで「FileSystemObject」オブジェクトを生成して、そのFolderExistsメソッドを使います。FolderExistsメソッドの引数には存在チェック対象のフォルダパスを与えます。
(構文)
- CreateObject("Scripting.FileSystemObject").FolderExists(CheckPath)
- Function IsFolder(ByVal CheckPath As String) As Boolean
- IsFolder = CreateObject("Scripting.FileSystemObject").FolderExists(CheckPath)
- End Function
(1-2) サンプルプログラム
上記の稼働確認のための簡単なサンプルプログラムをご紹介します。
(図121)
(サンプル)
- Public Sub checkFileFolderExist()
- '# フォルダの存在チェック対象のパス
- Dim checkPath1 As String: checkPath1 = "C:\Temp\ExistCheck\aaa" '# 存在するフォルダ
- Dim checkPath2 As String: checkPath2 = "C:\Temp\ExistCheck\bbb" '# 存在するフォルダ
- Dim checkPath3 As String: checkPath3 = "C:\Temp\ExistCheck\ccc" '# 存在しないフォルダ
- Dim checkPath4 As String: checkPath4 = "C:\Temp\ExistCheck\ddd" '# 存在するフォルダ
- '# フォルダの存在チェック結果をコンソールに出力
- Debug.Print checkPath1 & " exist check result : " & IsFolder(checkPath1)
- Debug.Print checkPath2 & " exist check result : " & IsFolder(checkPath2)
- Debug.Print checkPath3 & " exist check result : " & IsFolder(checkPath3)
- Debug.Print checkPath4 & " exist check result : " & IsFolder(checkPath4)
- '# ファイルの存在チェック
- Dim checkFile1 As String: checkFile1 = "C:\Temp\ExistCheck\001.txt" '# 存在するフォルダ
- Dim checkFile2 As String: checkFile2 = "C:\Temp\ExistCheck\002.txt" '# 存在しないフォルダ
- Dim checkFile3 As String: checkFile3 = "C:\Temp\ExistCheck\003.txt" '# 存在しないフォルダ
- Dim checkFile4 As String: checkFile4 = "C:\Temp\ExistCheck\004.txt" '# 存在するフォルダ
- '# ファイルの存在チェック結果をコンソールに出力
- Debug.Print checkFile1 & " exist check result : " & IsFile(checkFile1)
- Debug.Print checkFile2 & " exist check result : " & IsFile(checkFile2)
- Debug.Print checkFile3 & " exist check result : " & IsFile(checkFile3)
- Debug.Print checkFile4 & " exist check result : " & IsFile(checkFile4)
- End Sub
- '# フォルダの存在チェック用のファンクション
- Function IsFolder(ByVal CheckPath As String) As Boolean
- IsFolder = CreateObject("Scripting.FileSystemObject").FolderExists(CheckPath)
- End Function
- '# ファイルの存在チェック用のファンクション
- Function IsFile(ByVal CheckPath As String) As Boolean
- IsFile = CreateObject("Scripting.FileSystemObject").FileExists(CheckPath)
- End Function
上記のVBAプログラムを次のようなディレクトリに対して実行します。
(図122)
実行の結果、あるものは「true」、ないものは「false」で返却されます。
(動画122)