【VBA】プログレスバーで処理の進捗状況を表示する

PR

準備

1.「ユーザーフォーム」を新規作成
  右クリック→「挿入」→「ユーザーフォーム」

 

2.「プログレスバーコントロール」を追加
「ToolBoxのControls」を右クリック→「その他のコントロール」を選択し、
「Microsoft ProgressBar Control version X.X」にチェックを入れ「OK」



3.「ユーザーフォーム」上にProgressBarとLabelを配置
Labelの文字列は「実行中です…しばらくお待ちください」へ変更

PR

サンプルプログラム概要

・指定フォルダ配下にある全てのファイルを処理する
・処理の進捗状況を示すプログレスバーを表示する

PR

サンプルプログラム

'Sleep関数を実行可能にするため、1行目に記載
Private Declare Sub Sleep Lib "kernel32" (ByVal ms As Long)

Sub progressSelectDialogSample()
    
    Const SLEEP_TIME As Long = 1000
    Dim fso As Object
    Dim objFolder As Object
    Dim folderPath As String
    Dim fileName As Variant
    Dim fileCompleteCount As Double
    
    'フォルダを選択するダイアログを表示
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = 0 Then
            MsgBox "キャンセルされました"
            Exit Sub
        End If
        folderPath = .SelectedItems(1)
    End With
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set objFolder = fso.GetFolder(folderPath)
    
    '「ユーザーフォーム」を表示
    UserForm1.Show vbModeless
    'プログレスバーの最小値を設定
    UserForm1.ProgressBar1.Min = 1
    'プログレスバーの最大値を設定
    UserForm1.ProgressBar1.Max = objFolder.Files.count

    '全ファイル分繰り返し
    fileCompleteCount = 0
    For Each fileName In objFolder.Files
        '「ユーザーフォーム」上のラベルを表示させるためにDoEventsが必要
        DoEvents
        'ファイルに対する処理を記載
        Debug.Print fileName
        Sleep SLEEP_TIME
        '進捗状況を更新
        fileCompleteCount = fileCompleteCount + 1
        UserForm1.ProgressBar1.Value = fileCompleteCount
    Next
    
    '「ユーザーフォーム」を非表示
    Unload UserForm1
End Sub

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