【VBA高速化】開始と終了のルーチン呼び出し
作成日:2022-12-02
更新日:2025-10-04

開始・終了・中断
' 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
- Microsoft. (n.d.). Application.Calculation property (Excel).
https://learn.microsoft.com/en-us/office/vba/api/excel.application.calculation - Microsoft. (n.d.). End statement (VBA).
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/end-statement - de Bruin, R. (n.d.). Speed up your code & Excel(画面更新停止・イベント無効化・計算手動の実務的ガイド)
https://www.rondebruin.nl/win/s9/win005.htm
| Calculation Mode|計算モード |
| State Restoration|状態復元 |
| Nesting Safety|ネスト安全性 |
| Error Handling|エラーハンドリング |
| Side Effects|副作用 |
If you respect user settings,
keep and restore them.
ユーザー設定を尊重するなら
保存して復元
keep and restore them.
ユーザー設定を尊重するなら
保存して復元
2022-12-02
編集後記:
この記事の内容がベストではないかもしれません。