例: Error 関数

この例では、Err 関数、Err ステートメント、Error 関数、Error ステートメントを使用します。ユーザーは、1 から 100 までの数値を 1 つ入力するように要求されます。ユーザーの入力を 4 バイトの Single 型に変換できない場合はエラーとなります。この例では、1 から 100 までの範囲に含まれない数値が入力された場合のエラーが、さらに 2 種類定義されます。

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.