【VBAレシピ】指定したフォルダ以下の中から、ファイル名を完全一致で検索して、ファイルパスを返す。
folderPath : 検索をするフォルダーのパス。
searchFileName : 検索するファイルの名前。拡張子含む。
見つからなければ空文字を返す。
フォルダ、サブフォルダ内に同名のファイルが複数ある場合、最初に見つかったファイルのみ返す。検索順はファイル名の昇順。
Function getFilePath(folderPath As String, searchFileName As String) As String Set fso = CreateObject("Scripting.FileSystemObject") 'folderPath内のファイルを検索 For Each file In fso.getFolder(folderPath).Files If file.Name = searchFileName Then getFilePath = file.Path Exit Function End If Next 'folderPath内のサブフォルダを再帰的に検索 For Each folder In fso.getFolder(folderPath).SubFolders Dim filePath As String filePath = getFilePath(folder.Path, searchFileName) If (filePath <> "") Then getFilePath = filePath Exit Function End If Next getFilePath = "" End Function
拡張子無しで検索するバージョン
Function getFilePathWithoutExtension(folderPath As String, searchFileName As String) As String Set fso = CreateObject("Scripting.FileSystemObject") 'folderPath内のファイルを検索 For Each file In fso.getFolder(folderPath).Files If fso.getBaseName(file.Name) = searchFileName Then 'この行だけ変更 getFilePath = file Exit Function End If Next 'folderPath内のサブフォルダを再帰的に検索 For Each folder In fso.getFolder(folderPath).SubFolders Dim filePath As String filePath = getFilePath(folder.Path, searchFileName) If (filePath <> "") Then getFilePath = filePath Exit Function End If Next getFilePath = "" End Function