【VBA】ダイアログで指定したフォルダ配下の全てのテキストファイルに対して処理を行う

PR

ポイント

・ここでは「Application.FileDialog」を使用

PR

サンプルプログラム

Sub folderSelectDialogSample()
    
    Const TARGET_FILE_TYPE As String = "\*.txt"
    Dim folderPath As String
    Dim fileName As String
    
    'フォルダを選択するダイアログを表示
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = 0 Then
            MsgBox "キャンセルされました"
            Exit Sub
        End If
        folderPath = .SelectedItems(1)
    End With
    
    '1ファイル目を取得
    fileName = Dir(folderPath & TARGET_FILE_TYPE, vbNormal)
    '全テキストファイル分繰り返し
    Do While fileName <> ""
        'ファイルに対する処理を記載する
        Debug.Print fileName
        fileName = Dir()
    Loop
End Sub

タイトルとURLをコピーしました