VBA エラー処理に適したパターンは何ですか? [closed] 質問する

VBA エラー処理に適したパターンは何ですか? [closed] 質問する

VBA でのエラー処理に適したパターンは何ですか?

特に、このような状況ではどうすればよいでしょうか。

... some code ...
... some code where an error might occur ...
... some code ...
... some other code where a different error might occur ...
... some other code ...
... some code that must always be run (like a finally block) ...

両方のエラーを処理し、エラーが発生した可能性のあるコードの後で実行を再開したい。また、最後のfinallyコードはいつも実行 - 以前にどのような例外がスローされたかに関係なく。この結果を達成するにはどうすればよいですか?

ベストアンサー1

VBA でのエラー処理

  • On Error Goto エラー ハンドラ ラベル
  • ResumeNext|エラー ハンドラ ラベル
  • On Error Goto 0(現在のエラー ハンドラーを無効にします)
  • Err物体

オブジェクトErrのプロパティは通常、エラー処理ルーチンでゼロまたは長さゼロの文字列にリセットされますが、 を使用して明示的に行うこともできますErr.Clear

エラー処理ルーチン内のエラーが終了しています。

513~65535の範囲はユーザーエラーに使用できます。カスタムクラスエラーの場合は、vbObjectErrorエラー番号に追加します。詳細については、Microsoftのドキュメントを参照してください。Err.Raiseそしてそのエラー番号のリスト

実装されていないインターフェースメンバーの場合派生クラスの場合は、定数 を使用する必要がありますE_NOTIMPL = &H80004001


Option Explicit

Sub HandleError()
  Dim a As Integer
  On Error GoTo errMyErrorHandler
    a = 7 / 0
  On Error GoTo 0
  
  Debug.Print "This line won't be executed."
  
DoCleanUp:
  a = 0
Exit Sub
errMyErrorHandler:
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub

Sub RaiseAndHandleError()
  On Error GoTo errMyErrorHandler
    ' The range 513-65535 is available for user errors.
    ' For class errors, you add vbObjectError to the error number.
    Err.Raise vbObjectError + 513, "Module1::Test()", "My custom error."
  On Error GoTo 0
  
  Debug.Print "This line will be executed."

Exit Sub
errMyErrorHandler:
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
  Err.Clear
Resume Next
End Sub

Sub FailInErrorHandler()
  Dim a As Integer
  On Error GoTo errMyErrorHandler
    a = 7 / 0
  On Error GoTo 0
  
  Debug.Print "This line won't be executed."
  
DoCleanUp:
  a = 0
Exit Sub
errMyErrorHandler:
  a = 7 / 0 ' <== Terminating error!
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub

Sub DontDoThis()
  
  ' Any error will go unnoticed!
  On Error Resume Next
  ' Some complex code that fails here.
End Sub

Sub DoThisIfYouMust()
  
  On Error Resume Next
  ' Some code that can fail but you don't care.
  On Error GoTo 0
  
  ' More code here
End Sub

おすすめ記事