はじめに
指定したフォルダ内のファイル情報を取得しリストアップする。
プロシジャーの説明
サブフォルダも3階層まで調べることができます。このコードは、指定フォルダ内とそのサブフォルダ内のファイル情報(ファイル名、パスなど)をリストアップするものです。
サンプル1
Option Explicit
Sub GetFolderFileInfo()
' -------------------------------------------------------------
' 指定したフォルダ内のファイル情報を取得し、
' サブフォルダも3階層まで調べることができます。
' このコードは、指定フォルダ内とそのサブフォルダ内のファイル情報
' (ファイル名、パスなど)をリストアップするものです。
' -------------------------------------------------------------
Dim FolderPath As String
Dim ws As Worksheet
Dim RowIndex As Long
' フォルダパスを指定
FolderPath = "C:\ALLlib\エクセルマクロ"
Set ws = ThisWorkbook.Sheets(1) ' 結果を出力するシート
RowIndex = 1 ' データの開始行
' シートのヘッダー
ws.Cells(RowIndex, 1).Value = "ファイル名"
ws.Cells(RowIndex, 2).Value = "ファイルパス"
RowIndex = RowIndex + 1
' フォルダ内のファイルをリスト化
Call ListFiles(FolderPath, ws, RowIndex, 1)
MsgBox "完了しました!"
End Sub
Sub ListFiles(ByVal FolderPath As String, ByRef ws As Worksheet, ByRef RowIndex As Long, ByVal Depth As Integer)
Dim FSO As Object
Dim Folder As Object
Dim SubFolder As Object
Dim File As Object
' FileSystemObjectを設定
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Folder = FSO.GetFolder(FolderPath)
' フォルダ内のファイルを取得
For Each File In Folder.Files
ws.Cells(RowIndex, 1).Value = File.Name
ws.Cells(RowIndex, 2).Value = File.Path
RowIndex = RowIndex + 1
Next File
' サブフォルダを再帰的に処理 (3階層まで)
If Depth < 3 Then
For Each SubFolder In Folder.Subfolders
Call ListFiles(SubFolder.Path, ws, RowIndex, Depth + 1)
Next SubFolder
End If
End Sub