0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

エクセルVBAでのTryCatchFinally

Posted at

エクセルVBAにTryCatchはない

エクセルVBAには、他言語にあるようなtryCatchFinallyは無いが、VBA自体の例外処理を使って、擬似的にTryCatchFinallyを表現できる。

TryCatchFinallyのやり方

まずはコードから

TryCatchFinallyDemo
Sub TryCatchFinallyDemo()
    On Error GoTo Catch

    ' エラーが発生する可能性のある処理

    GoSub Finally

Catch:
    ' エラーの処理

    GoSub Finally

Finally:
    ' Finally処理
End Sub

説明

On Error GoToはエラーが発生した時、ラベルの位置に処理が移るため、Tryと同義になります。
ちなみに、ラベルに0を指定すれば、直前に指定したOn Error GoToを無効化できるため、Tryブロックでコードを囲むといったことができるようになります。

On Error GoTo [ラベル]

On Error GoToで指定したラベルで例外処理をします。いわゆる、Catchの役割です。

Catch:
    ' エラーの処理

Finallyラベルでは、例外の有無に関わらず行いたい処理を書きます。
Finallyが必要でない場合も必ずラベルは書くようにしてください。理由は後述します。

Finally:
    ' Finally処理

今回の肝となる部分がGoSubです。
VBAのラベルは、あくまでも目次的なものであり、直前にExit Subなどを記載していない場合、実行されてしまいます。
そのため、処理の最後とCatchラベルの最後には必ず下記のコードを挿入してください。
そして、Finallyラベルは必ずEnd Subの直前に書いてください。
こうすることで、例外の有無に関わらず、Finallyラベル以下が実行されます。

GoSub Finally

最後に

もし、誰かの役に立てたなら幸いです。

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?