【VBA】存在確認

 #VBA 
'存在確認
Function ExistCheck(ByRef パス As String) As Boolean
   
   Dim fso As Object
   Set fso = CreateObject("Scripting.FileSystemObject")
   
   If fso.FileExists(パス) Then
       ExistCheck = True
   ElseIf fso.FolderExists(パス) Then
       ExistCheck = True
   Else
       ExistCheck = False
   End If
   
   If Not fso Is Nothing Then Set fso = Nothing
End Function
 #VBA 
'複数パスから存在するパスを返す
Function GetExistPath(パス As Variant) As String
   Dim strPath As Variant
   For Each strPath In パス
       If ExistCheck(CStr(strPath)) Then
           GetExistPath = strPath
           Exit For
       End If
   Next
End Function
 #VBA 
'ユーザ定義関数の説明登録
Sub AddUDFToCustomCategory()
   
   'オプションの設定方法は下記参照
   '   https://docs.microsoft.com/ja-jp/office/vba/api/excel.application.macrooptions
   
   Application.MacroOptions _
         Macro:="ExistCheck" _
       , Description:="対象パスの存在確認をします" _
       , Category:=9 _
       , ArgumentDescriptions:=Array( _
                                     "を指定します" _
                               )

   Application.MacroOptions _
         Macro:="GetExistPath" _
       , Description:="配列内から最初に存在するパスの文字列を取得します" _
       , Category:=9 _
       , ArgumentDescriptions:=Array( _
                                     "を指定します" _
                                     & vbCrLf & "入力例1){""パス1"",""パス2"",""パス3""}" _
                                     & vbCrLf & "入力例2)A1:A5" _
                               )

End Sub

この記事が気に入ったらサポートをしてみませんか?