Number 属性

返回或设置指定错误的数值。 NumberErr 对象的默认属性。 读/写。

备注

从对象返回用户定义的错误时,通过将所选数字作为错误代码添加到 vbObjectError 常量来设置 Err.Number。 例如,使用以下代码将数字 1051 作为错误代码返回:

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

示例

第一个示例阐释了错误处理例程中 Number 属性的典型用法。 第二个示例检查 Err 对象的 Number 属性以确定 Automation 对象所返回的错误是否已由该对象定义,或是否已将其映射到 Visual Basic 所定义的错误。

请注意,常量 vbObjectError 是一个很大的负数,对象可将该负数添加到其自己的错误代码中来指示错误将由服务器定义。 因此,从 Err.Number 中减去该负数可将其从结果中去除。

如果错误是对象定义的,则基数将保留在 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 支持和反馈,获取有关如何接收支持和提供反馈的指南。