ファイル、フォルダーを下層のフォルダーも含めて参照する

FileSystemObject オブジェクト 続き

ファイル、フォルダーを参照するでは、現在のExcleファイルがあるフォルダーについて参照しましたが、今度は下層のフォルダーとファイルについても参照します。


Private Rcnt, Ccnt As Integer

Sub findFolderandFile()

    Rcnt = 1
    Ccnt = 1
    Dim folderpath As String
    folderpath = ActiveWorkbook.Path

    ShowFolderandFile folderpath

End Sub

Sub ShowFolderandFile(folderpath)
    Dim i As Integer
    Dim ii As Integer
    Dim j As Integer
    
    Dim FolderCol, FileCol As Object
    Dim FolderItem, FileItem As Object
    
    Set FileCol = CreateObject("Scripting.FileSystemObject").GetFolder(folderpath).Files
    
    Cells(Rcnt, Ccnt) = folderpath
    Rcnt = Rcnt + 1

    For Each FileItem In FileCol                               'ファイルカウントルーチン
        Cells(Rcnt, Ccnt + 1).Value = FileItem.Name
        Cells(Rcnt, Ccnt + 2).Value = FileItem.Size
        Rcnt = Rcnt + 1
    Next

    Set FolderCol = CreateObject("Scripting.FileSystemObject").GetFolder(folderpath).SubFolders
    
    For Each FolderItem In FolderCol                           'フォルダーカウントルーチン
        Ccnt = Ccnt + 1
        nextfolderpath = folderpath & "\" & FolderItem.Name
        ShowFolderandFile nextfolderpath
    Next
    
    Ccnt = Ccnt - 1

    Set FolderCol = Nothing
    Set FileCol = Nothing
    Set FolderItem = Nothing
    Set FileItem = Nothing
    
End Sub


結果
実行結果の例

参考HP:アプリケーションとしてのVBA
ほとんど丸写しです。(^_^;)

Excel VBAのチップス一覧へ戻る

ツイート
このエントリーをはてなブックマークに追加
inserted by FC2 system