Dir フォルダ一覧を作成するExcel関数

前回、Dir関数を使い指定したフォルダ内のファイル検索を行いましたが、今回はフォルダ一覧検索を行います。
2番目の引数「取得したいファイルの属性」には、vbDirectory を指定します。使い方はファイル検索と同じです。


Homeに戻る > Excel 関数のTipsへ

Excel実行画面

「フォルダ一覧の作成」コマンドボタンをクリックするとVBAが開始します。
フォルダ一覧の作成

フォルダ選択ダイアログボックスが開くので一覧を作成したいフォルダを選択します。
フォルダ選択ダイアログボックス

一覧を作成したいフォルダを選択すると、フォルダ内のフォルダ一覧がB7セルから下に表示されます。
フォルダ内のフォルダ一覧


Excel VBAコード

Option Explicit

'フォルダ選択ダイアログExcel標準モジュールコード (初期フォルダを指定する方法)
Public Function SelectFolder_FileDialog(iniDir As String) As String
    Dim s1 As String
    
    'フォルダ選択ダイアログ
    With Application.FileDialog(msoFileDialogFolderPicker)
        'タイトル
        .Title = "フォルダを選択してください"
        '初期フォルダ
        .InitialFileName = iniDir
        If .Show = -1 Then
            '選択された
            s1 = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)
            If Right$(s1, 1) <> "\" Then s1 = s1 + "\"
            SelectFolder_FileDialog = s1
        Else
            SelectFolder_FileDialog = ""
        End If
    End With
End Function

Private Sub MyGetFolder(sFolder As String)
    Dim sfina As String
    Dim lrow As Long
    
    lrow = 7
    sfina = Dir(sFolder, vbDirectory)
    Do While sfina <> ""
        Cells(lrow, 2) = sfina
        lrow = lrow + 1
        sfina = Dir
    Loop
End Sub

Private Sub CommandButton1_Click()
    Dim sFolder As String
    
    sFolder = SelectFolder_FileDialog("c:\")
    If sFolder <> "" Then
        MyGetFolder sFolder
    End If
End Sub

[関連リンク]
フォルダー選択ダイアログ
フォルダ内のファイルを取得する


Homeに戻る > Excel 関数のTipsへ

■■■
このサイトの内容を利用して発生した、いかなる問題にも一切責任は負いませんのでご了承下さい
■■■
当ホームページに掲載されているあらゆる内容の無許可転載・転用を禁止します


Copyright (c) Excel-Excel ! All rights reserved