On Error GoTo ... Resume Statement

發生錯誤時啟動錯誤處理常式,或恢復程式執行。

語法

On {[本機] Error GoTo Labelname | GoTo 0 | Resume Next}

參數:

GoTo Labelname:發生錯誤時,讓錯誤處理常式跳換到「Labelname」行處開始執行。

Resume Next:發生錯誤時,程式繼續執行出錯陳述式後面的陳述式。

GoTo 0:在目前程序中停用錯誤處理程式。

本機:「On error」範圍涵蓋全域,除非遭到其他「On error」陳述式取消,否則會保持在使用中。而「On Local error」則適用於本機,僅限於呼叫的常式。本機錯誤處理會覆寫任何先前的全域設定。當呼叫的常式存在時,本機錯誤處理會自動取消,而且會復原所有先前的全域設定。

On Error GoTo 陳述式用來反應出現在巨集內的錯誤。

示例:

Sub ExampleReset

On Error GoTo ErrorHandler

Dim iNumber As Integer

Dim iCount As Integer

Dim sLine As String

Dim aFile As String

    aFile = "c:\data.txt"

    iNumber = Freefile

    Open aFile For Output As #iNumber

    Print #iNumber, "This is a line of text"

    Close #iNumber

    iNumber = Freefile

    Open aFile For Input As iNumber

    For iCount = 1 To 5

        Line Input #iNumber, sLine

        If sLine <>"" Then

            Rem

        End If

    Next iCount

    Close #iNumber

    Exit Sub

ErrorHandler:

    Reset

    MsgBox "All files will be closed",0,"Error"

End Sub