【Excel VBA】サブフォルダを含めてファイルパスを列挙する

サブフォルダを含めてファイルパスを列挙する方法について説明します。

ファイルパスを列挙する方法


ファイルパスを列挙するメソッド


サブフォルダを含めてファイルパスを列挙するコードです。


VBAからコマンドプロンプトのDirコマンドを呼び出し、サブフォルダを含めてファイルパスを列挙して配列で返却します。


'サブフォルダを含めてファイルを列挙する
'dirPath:親フォルダのパス
'exts:列挙対象の拡張子(配列)
'返却値:ファイルパス(配列)
Function FileEnumeration(dirPath As String, exts As Variant)
'コマンド文を作成
Dim commandList As Variant: ReDim commandList(UBound(exts))
Dim i As Long
For i = 0 To 1
commandList(i) = """" & dirPath & "\*." & exts(i) & """"
Next
'WshShellオブジェクトの作成
Dim wsh As Object: Set wsh = CreateObject("WScript.Shell")
'WshShellでDirコマンドを実行
Dim result As String
result = wsh.Exec("%ComSpec% /c " & "dir /s /b /a-d " _
& Join(commandList, " ")).StdOut.ReadAll
'WshShellオブジェクトを解放
Set wsh = Nothing
'結果を配列で返却
If Len(result) = 0 Then Exit Function
result = Left(result, Len(result) - 1)
FileEnumeration = Split(result, vbCrLf)
End Function

サンプルコード


先ほどのメソッドを利用して、対象フォルダ内の画像ファイル一覧をアクティブシートへ出力するサンプルです。


'ファイルを列挙した結果をアクティブシートへ出力
Sub Macro1()
'シートの内容を消す
Cells.Clear
'入力画面を表示
Dim dirPath As String
dirPath = InputBox("抽出対象のフォルダパスを入力してください")
If dirPath = "" Then Exit Sub
'対象パスの画像ファイルを列挙
Dim result As Variant
result = FileEnumeration(dirPath, Array("jpg", "png", "bmp", "tif", "webp", "heif"))
'列挙結果をシートへ出力
If Not IsArray(result) Then
MsgBox ("ファイルが見つかりませんでした")
Exit Sub
End If
Range(Cells(1, 1), Cells(UBound(result) + 1, 1)) = WorksheetFunction.Transpose(result)
End Sub
人気ブログランキング

この記事へのトラックバック