Examples: Err statement
This example uses the Err function, Err statement, Error function, and Error statement. The user is asked to enter a number between 1 and 100. If the user's entry cannot be converted to a 4-byte single, an error occurs. The example defines two additional errors for numeric entries not in the range 1 - 100.
Public x As Single
Const TOO_SMALL = 1001, TOO_BIG = 1002
Sub GetNum
Dim Num As String
On Error GoTo Errhandle
Num$ = InputBox$("Enter a value between 1 and 100:")
x! = CSng(Num$) ' Convert the string to a 4-byte single.
' Check the validity of the entry.
If x! < 1 Then
Error TOO_SMALL, "The number is too small or negative."
ElseIf x! > 100 Then
Error TOO_BIG, "The number is too big."
End If
' If the script gets here, the user made a valid entry.
MessageBox "Good job! " & Num$ & " is a valid entry."
Exit Sub
' The user did not make a valid entry.
' Display the error number and error message.
Errhandle:
' Use the Err function to return the error number and
' the Error$ function to return the error message.
MessageBox "Error" & Str(Err) & ": " & Error$
Exit Sub
End Sub
GetNum ' Call the GetNum sub.