【ExcelVBA】カレントフォルダ内のファイル一覧を出力

ExcelVBA,ファイルの操作,フォルダの操作

カレントフォルダ内のファイル名一覧を出力をする、サンプルマクロです。

イミディエイト画面に一行ずつ出力

FileSystemObjectを使う方法

Sub Sample2()

    Dim Path As String
    Path = ThisWorkbook.Path
    
    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    
    Dim f As Variant
    For Each f In FSO.GetFolder(Path).Files
        Debug.Print f
    Next f
    
    Set FSO = Nothing
    
End Sub

DIR関数を使う方法

Sub Sample()
  
    Call Recursive(ThisWorkbook.Path)
  
End Sub
  
Sub Recursive(Path As String)
    Dim SubF As Object
    Dim Buf As String
     
    Buf = Dir(Path & "\*.*")
    Do While Buf <> ""
        Debug.Print Path & "\" & Buf
        Buf = Dir()
    Loop
     
End Sub

※3行目にフォルダパスを記入します。

サブフォルダ内のファイル名も一覧に含めたいときは、以下を参照してください。