LoginSignup
2
3

More than 5 years have passed since last update.

【vba】LoopでApplication.StatusBarを使いすぎると極端に処理が遅くなる

Last updated at Posted at 2019-04-11

Application.StatusBarの表示をLoop毎に処理すると、
処理速度がかなり遅くなる。

よかれと思って処理状況を表示しようとすると、余計に処理が遅くなる。
別に悪さをする訳じゃないから、知らないときはなかなか気づけなかった…

ステータスバーの使用・未使用時の処理速度比較モジュール
Public Sub statusBarLoop()

    Sheets("work").Activate

    Dim count As Long
    count = 0

    Dim startTime As Double
    Dim endTime As Double

    Application.StatusBar = False

    '<<10万回ループする時間を計測(ステータスバー表示あり)>>
    startTime = Timer

    Do While count < 100000
        DoEvents
        count = count + 1
        Application.StatusBar = count & "回目のループ"
    Loop

    endTime = Timer

    'セルに処理時刻書き出し
    Cells(1, 1) = startTime
    Cells(2, 1) = endTime
    Cells(3, 1) = endTime - startTime


    '<<10万回ループする時間を計測(ステータスバー表示なし)>>
    startTime = Timer

    Do While count < 100000
        DoEvents
        count = count + 1
        'Application.StatusBar = count & "回目のループ"
    Loop

    endTime = Timer

    'セルに処理時刻書き出し
    Cells(1, 2) = startTime
    Cells(2, 2) = endTime
    Cells(3, 2) = endTime - startTime


    Application.StatusBar = False

    MsgBox "完了"

End Sub

<<処理結果>>

StatuBarあり StatusBarなし
開始 4732.443848 4888.368164
終了 4888.36377 4888.368164
処理時間 155.9199219 0

※単位は秒

比べるまでもなく、明らかにステータスバーなしのほうが早い。
表示させるなら、「10000ループごとに1回表示」くらいにしたほうがいい。

10000回に1回だけステータスバー表示サンプル
    Do While count < 100000
        DoEvents
        count = count + 1
        If count Mod 10000 = 0 Then
            Application.StatusBar = count & "回目のループ"
        End If
    Loop
2
3
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
2
3