Err Statement

See AlsoKZL6SV              Example3FDVGW>Low

Sets Err to a specific value.


Err = n


The argument n is either an integer between 1 and 32,767, inclusive, that specifies a run-timeCYRM35 error code or 0, which means no run-time error has occurred.

When running an application, Visual Basic uses Err to record whether or not a run-time error has occurred and what the error was.

Use the Err statement to set Err to a nonzero, integer value to communicate error information between procedures.  For example, you might use one of the run-time error codes not used by Visual Basic as an application-specific error code.  To determine which error codes are being used, use the Error[$] function and/or the Error statement.  You can create application-specific user-defined errors by working down from error code 32,767.

You can also set Err to 0 by using any form of the Resume or On Error statement or by executing an Exit Sub or Exit Function statement within an error handler.  In addition, the Error statement can set Err to any value to simulate any run-time error.

See Also

Err, Erl Functions3XXD805

Error, Error$ Functions5AEF2L

Error Statement5AEF2Y

Err Statement Example

As the example shows, with On Error Resume Next, errors are often handled in the lines of code immediately following the line where an error can occur.  Once the error has been handled, the Err statement clears the error by setting Err to 0 so subsequent error-handling code isn't inadvertently executed for an earlier error.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.


Sub Form_Click ()

   Dim FileName                               ' Declare variable.

   On Error Resume Next                       ' Set up error handler.

   FileName = InputBox("Enter a file name: ") ' Get file name.


      Err = 0                                 ' Clear any error.

      Open FileName For Input As #1           ' Open file.

      Select Case Err                         ' Handle error, if any.

         Case 0                               ' No error.

            MsgBox UCase(FileName) & " was found."   ' File found.

         Case 53, 75, 76                      ' Assorted file errors.

            FileName = InputBox("File was not found. Try again.")

         Case 52, 64                          ' Bad file name or number.

            FileName = InputBox("File name was invalid. Try again.")

         Case 68                              ' Device unavailable.

            FileName = InputBox("Device is not available. Try again.")

         Case 71                              ' Drive not ready.

            MsgBox "Close the drive door."

         Case Else                            ' Handle other cases.

            MsgBox "ERROR: Cannot continue!"  ' All fatal errors.


      End Select

   Loop Until Err = 0

   Close #1

End Sub