共用方式為


數性質

回傳或設定一個數值以指定錯誤。 NumberErr 物件的預設屬性。 讀取/寫入。

註解

當從物件回傳使用者自訂錯誤時,將你選擇的錯誤碼數字加入 vbObjectError 常數,設定 Err.Number。 例如,你使用以下代碼來回傳數字 1051 作為錯誤代碼:

Err.Raise Number := vbObjectError + 1051, Source := "SomeClass"

範例

第一個例子說明 了 Number 屬性在錯誤處理例程中的典型應用。 第二個範例檢視 Err 物件的 Number 屬性,以判斷 Automation 物件回傳的錯誤是否由該物件定義,或是映射為 Visual Basic 定義的錯誤。

請注意,常數 vbObjectError 是一個非常大的負數,物件會將它加到自身的錯誤碼上,以表示錯誤是由伺服器定義的。 因此,從 錯誤數 中減去它就會從結果中剔除。

若錯誤為物件定義,基數會保留在 MyError中,並顯示在訊息框中,與錯誤的原始來源一同顯示。 若 Err.Number 代表 Visual Basic 錯誤,則訊息框中會顯示 Visual Basic 錯誤編號。

' Typical use of Number property
Sub test()
    On Error GoTo out
    
    Dim x, y
    x = 1 / y    ' Create division by zero error
    Exit Sub
    out:
    MsgBox Err.Number
    MsgBox Err.Description
    ' Check for division by zero error
    If Err.Number = 11 Then
        y = y + 1
    End If
    Resume
End Sub
' Using Number property with an error from an 
' Automation object
Dim MyError, Msg
' First, strip off the constant added by the object to indicate one
' of its own errors.
MyError = Err.Number - vbObjectError
' If you subtract the vbObjectError constant, and the number is still 
' in the range 0-65,535, it is an object-defined error code.
If MyError > 0 And MyError < 65535 Then
    Msg = "The object you accessed assigned this number to the error: " _
             & MyError & ". The originator of the error was: " _
            & Err.Source & ". Press F1 to see originator's Help topic."
' Otherwise it is a Visual Basic error number.
Else
    Msg = "This error (# " & Err.Number & ") is a Visual Basic error" & _
            " number. Press Help button or F1 for the Visual Basic Help" _
            & " topic for this error."
End If
    MsgBox Msg, , "Object Error", Err.HelpFile, Err.HelpContext

另請參閱

支援和意見反應

有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應