【Excel VBA】サブフォルダを列挙する方法

スポンサーリンク

サブフォルダを列挙する方法について説明します。

サブフォルダを列挙する方法

サブフォルダを列挙するメソッド

サブフォルダを列挙するコードです。

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

'サブフォルダを列挙する
'dirPath:親フォルダのパス
'返却値:フォルダパス(配列)
Function DirEnumeration(dirPath As String)
    'WshShellオブジェクトの作成
    Dim wsh As Object: Set wsh = CreateObject("WScript.Shell")
     'WshShellでDirコマンドを実行
    Dim result As String
    result = wsh.Exec("%ComSpec% /c " & "dir /s /b /ad " & """" & dirPath & """").StdOut.ReadAll
    'WshShellオブジェクトを解放
     Set wsh = Nothing
    '結果を配列で返却
     If Len(result) = 0 Then Exit Function
     result = Left(result, Len(result) - 1)
     DirEnumeration = 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 = DirEnumeration(dirPath)
    '列挙結果をシートへ出力
    If Not IsArray(result) Then
        MsgBox ("サブフォルダが見つかりませんでした")
        Exit Sub
    End If
    Range(Cells(1, 1), Cells(UBound(result) + 1, 1)) = WorksheetFunction.Transpose(result)
End Sub
タイトルとURLをコピーしました