銀河鉄道

【VBA高速化】開始と終了のルーチン呼び出し

サムネイル
[VBA]開始と終了イベント停止と再開

開始・終了・中断

' Global variable for calculation mode|計算モード保持用
Private calc As Long

' Start process|開始処理
Public Sub StartMacro()
    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
        calc = .Calculation
        .Calculation = xlCalculationManual
    End With
End Sub

' End process|終了処理
Public Sub EndMacro()
    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .EnableEvents = True
        .Calculation = calc   ' ← 最後に戻す
    End With
    
    ' If waiting form is visible, close it|待機フォームが開いていたら閉じる
    If VBA.UserForms.Count > 0 Then
        On Error Resume Next
        Unload Frm_waiting
        On Error GoTo 0
    End If
End Sub

' Abort safely|中断処理(安全版)
Public Sub AllEnd()
    Call EndMacro
    Exit Sub
End Sub

Private calc As Longって?

Private calc As Longの役割

  • ユーザーの計算モード|calculation mode を元通りに戻すための保険。
  • 例外:毎回必ず xlCalculationAutomatic に戻したい運用なら 不要(ただしユーザー設定を上書きするリスク)。

calc is the safety pin that preserves the user’s setting.

Why it’s needed|なぜ必要?

  • ブックごとに 異なる計算モード|calculation mode があり得る
  • 開始前の状態|pre-state に戻すには、その値をどこかに保持する必要がある。
  • 「常に Automatic に戻す」と、ユーザーの意図した設定を壊す可能性がある。

When it could be unnecessary|いつ不要になり得るか

  • ポリシーとして「必ず xlCalculationAutomatic に戻す」なら、保持変数は要らない

Referenced Insights & Citations

| Calculation Mode|計算モード |
| State Restoration|状態復元 |
| Nesting Safety|ネスト安全性 |
| Error Handling|エラーハンドリング |
| Side Effects|副作用 |

If you respect user settings,
keep and restore them.

ユーザー設定を尊重するなら
保存して復元

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧