0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

VBA FileSystemObjectでディレクトリーを再帰的表示するマクロ

Last updated at Posted at 2021-08-25

Dirで探索するよりもこっちのほうが楽でした。

image.png

メインプログラム

Sub Main
Sub ボタン1_Click()

    Dim fso                 As FileSystemObject
    Dim fd                  As Object
    Dim file                As Object
    
    Dim location            As String
    
    
    Set fso = New Scripting.FileSystemObject
    Set fd = Application.FileDialog(msoFileDialogFolderPicker)
    
    If Not fd.Show Then
        MsgBox "ダイアログキャンセル", vbExclamation
        Exit Sub
    Else
        location = fd.SelectedItems(1)
    End If
    
    '親フォルダーのファイル探索
    For Each file In fso.GetFolder(location).files
           Debug.Print file.path
    Next file
    
    Call getAllFiles(location, fso)
    
End Sub

再帰的に表示する関数

Sub getAllFiles
Sub getAllFiles(ByVal path As String, ByRef fso As FileSystemObject)
    
    Dim files               As Object
    Dim file                As Object
    Dim fol                 As Object
    Dim folders             As Object
    
    Set folders = fso.GetFolder(path).SubFolders
    
    If IsObject(folders) Then
        For Each fol In folders

            Set files = fso.GetFolder(fol).files

            If IsObject(files) Then
                For Each file In files
                'ここで操作
                    Debug.Print file.path
 
                Next file
            End If
            
            Call getAllFiles(fol, fso)
            Set files = Nothing
            
        Next fol
    End If
    
End Sub

実行結果

huihi.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?