LoginSignup
0
0

More than 1 year has passed since last update.

VBA(Excel)で再帰的にファイルを開くには

Last updated at Posted at 2021-06-19

VBA(Excel)で再帰的にファイルを開くには

VBA(Excel)にて、再帰的にファイルを開くスニペット

Option Explicit

' メイン処理
Sub main()
    Dim targetFolder As String
    Dim fso As Object

    ' 画面更新の停止
    Application.ScreenUpdating = False
    'イベント抑止
    Application.EnableEvents = False


    ' 対象フォルダの指定
    targetFolder = ThisWorkbook.Worksheets(1).Range("B1").Value

    Set fso = CreateObject("Scripting.FileSystemObject")

    ' 対象フォルダ配下(サブフォルダ)の全ファイルに対する処理(再帰処理)
    Call loopAllFiles(targetFolder, fso)

    Set fso = Nothing

    'イベント抑止を解除
    Application.EnableEvents = True
    ' 画面更新の停止
    Application.ScreenUpdating = True
    MsgBox prompt:="処理が終了しました。"

End Sub

' 対象フォルダ配下(サブフォルダ)の全ファイルに対する処理(再帰処理)
Private Function loopAllFiles(targetFolder As String, fso As Object)

    Const FILE_TYPE_XLSX As String = "xlsx"
    Const FILE_TYPE_XLS As String = "xls"

    Dim folder As Object
    Dim file As Object

    'サブフォルダの数だけ再帰
    For Each folder In fso.getFolder(targetFolder).SubFolders
        Call loopAllFiles(folder.Path, fso)
    Next folder

    'ファイルの数分繰り返し
    For Each file In fso.getFolder(targetFolder).Files

        Dim extentionName As String
        extentionName = fso.GetExtensionName(file.Name)

        If LCase(extentionName) = FILE_TYPE_XLS Or LCase(extentionName) = FILE_TYPE_XLSX Then
            ' Excelファイルに対する処理
            Call execExcelFile(file)
        End If

    Next file

End Function

' Excelファイルに対する処理
Private Function execExcelFile(file As Object)

    Dim wkbook As Workbook

    Set wkbook = Workbooks.Open(Filename:=file.Path, UpdateLinks:=0, IgnoreReadOnlyRecommended:=True, ReadOnly:=True)

    Debug.Print wkbook.Name

    wkbook.Close SaveChanges:=False

End Function

参考資料

【VBA】【再帰】指定フォルダ配下(サブフォルダ含む)の全てのExcelファイルに対して、処理を行う

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