Access vba при ошибке

In this Article

  • VBA Errors Cheat Sheet
    • Errors
  • VBA Error Handling
  • VBA On Error Statement
    • On Error GoTo 0
    • On Error Resume Next
    • Err.Number, Err.Clear, and Catching Errors
    • On Error GoTo Line
  • VBA IsError
  • If Error VBA
  • VBA Error Types
    • Runtime Errors
    • Syntax Errors
    • Compile Errors
    • Debug > Compile
    • OverFlow Error
  • Other VBA Error Terms
    • VBA Catch Error
    • VBA Ignore Error
    • VBA Throw Error / Err.Raise
    • VBA Error Trapping
    • VBA Error Message
    • VBA Error Handling in a Loop
  • VBA Error Handling in Access

VBA Errors Cheat Sheet

Errors

On Error – Stop code and display error

On Error Goto 0

On Error – Skip error and continue running

On Error Resume Next

On Error – Go to a line of code [Label]

On Error Goto [Label]

Clears (Resets) Error

On Error GoTo1

Show Error number

MsgBox Err.Number

Show Description of error

MsgBox Err.Description

Function to generate own error

Err.Raise

See more VBA “Cheat Sheets” and free PDF Downloads

VBA Error Handling

VBA Error Handling refers to the process of anticipating, detecting, and resolving VBA Runtime Errors. The VBA Error Handling process occurs when writing code, before any errors actually occur.

VBA Runtime Errors are errors that occur during code execution. Examples of runtime errors include:

  • Referencing a non-existent workbook, worksheet, or other object (Run-time Error 1004)
  • Invalid data ex. referencing an Excel cell containing an error (Type Mismatch – Run-time Error 13)
  • Attempting to divide by zero

VBA On Error Statement

Most VBA error handling is done with the On Error Statement. The On Error statement tells VBA what to do if it encounters an error. There are three On Error Statements:

  • On Error GoTo 0
  • On Error Resume Next
  • On Error GoTo Line

On Error GoTo 0

On Error GoTo 0 is VBA’s default setting. You can restore this default setting by adding the following line of code:

On Error GoTo 0

When an error occurs with On Error GoTo 0, VBA will stop executing code and display its standard error message box.

vba runtime error 13

Often you will add an On Error GoTo 0 after adding On Error Resume Next error handling (next section):

Sub ErrorGoTo0()

On Error Resume Next
    ActiveSheet.Shapes("Start_Button").Delete
On Error GoTo 0

'Run More Code

End Sub

On Error Resume Next

On Error Resume Next tells VBA to skip any lines of code containing errors and proceed to the next line.

On Error Resume Next

Note: On Error Resume Next does not fix an error, or otherwise resolve it. It simply tells VBA to proceed as if the line of code containing the error did not exist. Improper use of On Error Resume Next can result in unintended consequences.

A great time to use On Error Resume Next is when working with objects that may or may not exist. For example, you want to write some code that will delete a shape, but if you run the code when the shape is already deleted, VBA will throw an error. Instead you can use On Error Resume Next to tell VBA to delete the shape if it exists.

On Error Resume Next
    ActiveSheet.Shapes("Start_Button").Delete
On Error GoTo 0

Notice we added On Error GoTo 0 after the line of code containing the potential error. This resets the error handling.

In the next section we’ll show you how to test if an error occurred using Err.Number, giving you more advanced error handling options.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Err.Number, Err.Clear, and Catching Errors

Instead of simply skipping over a line containing an error, we can catch the error by using On Error Resume Next and Err.Number.

Err.Number returns an error number corresponding with the type of error detected. If there is no error, Err.Number = 0.

For example, this procedure will return “11” because the error that occurs is Run-time error ’11’.

Sub ErrorNumber_ex()

On Error Resume Next
ActiveCell.Value = 2 / 0
MsgBox Err.Number

End Sub

vba run-time error 11 err.number

Error Handling with Err.Number

The true power of Err.Number lies in the ability to detect if an error occurred (Err.Number <> 0).  In the example below, we’ve created a function that will test if a sheet exists by using Err.Number.

Sub TestWS()
    MsgBox DoesWSExist("test")
End Sub

Function DoesWSExist(wsName As String) As Boolean
    Dim ws As Worksheet
    
    On Error Resume Next
    Set ws = Sheets(wsName)
    
    'If Error WS Does not exist
    If Err.Number <> 0 Then
        DoesWSExist = False
    Else
        DoesWSExist = True
    End If

    On Error GoTo -1
End Function

Note: We’ve added a On Error GoTo -1 to the end which resets Err.Number to 0 (see two sections down).

With On Error Resume Next and Err.Number, you can replicate the “Try” & “Catch” functionality of other programming languages.

On Error GoTo Line

On Error GoTo Line tells VBA to “go to” a labeled line of code when an error is encountered.  You declare the Go To statement like this (where errHandler is the line label to go to):

On Error GoTo errHandler

and create a line label like this:

errHandler:

Note: This is the same label that you’d use with a regular VBA GoTo Statement.

Below we will demonstrate using On Error GoTo Line to Exit a procedure.

On Error Exit Sub

You can use On Error GoTo Line to exit a sub when an error occurs.

You can do this by placing the error handler line label at the end of your procedure:

Sub ErrGoToEnd()

On Error GoTo endProc

'Some Code
    
endProc:
End Sub

or by using the Exit Sub command:

Sub ErrGoToEnd()

On Error GoTo endProc

'Some Code
GoTo skipExit
    
endProc:
Exit Sub

skipExit:

'Some More Code

End Sub

Err.Clear, On Error GoTo -1,  and Resetting Err.Number

After an error is handled, you should generally clear the error to prevent future issues with error handling.

After an error occurs, both Err.Clear and On Error GoTo -1 can be used to reset Err.Number to 0. But there is one very important difference: Err.Clear does not reset the actual error itself, it only resets the Err.Number.

What does that mean?  Using Err.Clear, you will not be able to change the error handling setting. To see the difference, test out this code and replace On Error GoTo -1 with Err.Clear:

Sub ErrExamples()

    On Error GoTo errHandler:
        
    '"Application-defined" error
    Error (13)
    
Exit Sub
errHandler:
    ' Clear Error
    On Error GoTo -1
    
    On Error GoTo errHandler2:
    
    '"Type mismatch" error
    Error (1034)
    
Exit Sub
errHandler2:
    Debug.Print Err.Description
End Sub

Typically, I recommend always using On Error GoTo -1, unless you have a good reason to use Err.Clear instead.

VBA On Error MsgBox

You might also want to display a Message Box on error.  This example will display different message boxes depending on where the error occurs:

Sub ErrorMessageEx()
 
Dim errMsg As String
On Error GoTo errHandler

    'Stage 1
    errMsg = "An error occured during the Copy & Paste stage."
    'Err.Raise (11)
    
    'Stage 2
    errMsg = "An error occured during the Data Validation stage."
    'Err.Raise (11)
     
    'Stage 3
    errMsg = "An error occured during the P&L-Building and Copy-Over stage."
    Err.Raise (11)
     
    'Stage 4
    errMsg = "An error occured while attempting to log the Import on the Setup Page"
    'Err.Raise (11)

    GoTo endProc
    
errHandler:
    MsgBox errMsg
   
endProc:
End Sub

Here you would replace Err.Raise(11) with your actual code.

VBA IsError

Another way to handle errors is to test for them with the VBA ISERROR Function. The ISERROR Function tests an expression for errors, returning TRUE or FALSE if an error occurs.

Sub IsErrorEx()
    MsgBox IsError(Range("a7").Value)
End Sub

VBA Programming | Code Generator does work for you!

If Error VBA

You can also handle errors in VBA with the Excel IFERROR Function.  The IFERROR Function must be accessed by using the WorksheetFunction Class:

Sub IfErrorEx()

Dim n As Long
n = WorksheetFunction.IfError(Range("a10").Value, 0)

MsgBox n
End Sub

This will output the value of Range A10, if the value is an error, it will output 0 instead.

VBA Error Types

Runtime Errors

As stated above:

VBA Runtime Errors are errors that occur during code execution. Examples of runtime errors include:

  • Referencing a non-existent workbook, worksheet, or other object
  • Invalid data ex. referencing an Excel cell containing an error
  • Attempting to divide by zero

vba runtime error 13

You can “error handle” runtime errors using the methods discussed above.

Syntax Errors

VBA Syntax Errors are errors with code writing. Examples of syntax errors include:

  • Mispelling
  • Missing or incorrect punctuation

The VBA Editor identifies many syntax errors with red highlighting:

vba syntax error example

The VBA Editor also has an option to “Auto Syntax Check”:

vba syntax error option

When this is checked, the VBA Editor will generate a message box alerting you syntax errors after you enter a line of code:

vba syntax compile error

I personally find this extremely annoying and disable the feature.

Compile Errors

Before attempting to run a procedure, VBA will “compile” the procedure. Compiling transforms the program from source code (that you can see) into executable form (you can’t see).

VBA Compile Errors are errors that prevent the code from compiling.

A good example of a compile error is a missing variable declaration:

vba compile error variable

Other examples include:

  • For without Next
  • Select without End Select
  • If without End If
  • Calling a procedure that does not exist

Syntax Errors (previous section) are a subset of Compile Errors.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Debug > Compile

Compile errors will appear when you attempt to run a Procedure. But ideally, you would identify compile errors prior to attempting to run the procedure.

You can do this by compiling the project ahead of time. To do so, go to Debug > Compile VBA Project.

vba debug compile

The compiler will “go to” the first error. Once you fix that error, compile the project again. Repeat until all errors are fixed.

You can tell that all errors are fixed because Compile VBA Project will be grayed out:

vba compile vbaproject

OverFlow Error

The VBA OverFlow Error occurs when you attempt to put a value into a variable that is too large. For example, Integer Variables can only contain values between -32,768 to 32,768. If you enter a larger value, you’ll receive an Overflow error:

vba overflow error

Instead, you should use the Long Variable to store the larger number.

Other VBA Error Terms

VBA Catch Error

Unlike other programming languages, In VBA there is no Catch Statement. However, you can replicate a Catch Statement by using On Error Resume Next and If Err.Number <> 0 Then. This is covered above in Error Handling with Err.Number.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA Ignore Error

To ignore errors in VBA, simply use the On Error Resume Next statement:

On Error Resume Next

However, as mentioned above, you should be careful using this statement as it doesn’t fix an error, it just simply ignores the line of code containing the error.

VBA Throw Error / Err.Raise

To through an error in VBA, you use the Err.Raise method.

This line of code will raise Run-time error ’13’: Type mismatch:

Err.Raise (13)

vba runtime error 13

VBA Error Trapping

VBA Error Trapping is just another term for VBA Error Handling.

VBA Error Message

A VBA Error Message looks like this:

vba runtime error 13

When you click ‘Debug’, you’ll see the line of code that is throwing the error:

vba raise error

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA Error Handling in a Loop

The best way to error handle within a Loop is by using On Error Resume Next along with Err.Number to detect if an error has occurred (Remember to use Err.Clear to clear the error after each occurrence).

The example below will divide two numbers (Column A by Column B) and output the result into Column C. If there’s an error, the result will be 0.

Sub test()
Dim cell As Range

On Error Resume Next
For Each cell In Range("a1:a10")

    'Set Cell Value
    cell.Offset(0, 2).Value = cell.Value / cell.Offset(0, 1).Value
    
    'If Cell.Value is Error then Default to 0
    If Err.Number <> 0 Then
         cell.Offset(0, 2).Value = 0
         Err.Clear
    End If
 Next
End Sub

VBA Error Handling in Access

All of the above examples work exactly the same in Access VBA as in Excel VBA.

Function DelRecord(frm As Form)
'this function is used to delete a record in a table from a form
   On Error GoTo ending
   With frm
      If .NewRecord Then
         .Undo
         Exit Function
      End If
   End With
   With frm.RecordsetClone
      .Bookmark = frm.Bookmark
      .Delete
      frm.Requery
   End With
   Exit Function
   ending:
   End
End Function

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Elements of run-time error handling

vbaac10.chm5186924

vbaac10.chm5186924

access

a0e06a1e-2709-aa51-92d0-340788a31a8a

09/21/2018

medium

Elements of run-time error handling

Errors and error handling

When you are programming an application, you need to consider what happens when an error occurs. An error can occur in your application for one of two of reasons. First, some condition at the time the application is running makes otherwise valid code fail. For example, if your code attempts to open a table that the user has deleted, an error occurs. Second, your code may contain improper logic that prevents it from doing what you intended. For example, an error occurs if your code attempts to divide a value by zero.

If you’ve implemented no error handling, then Visual Basic halts execution and displays an error message when an error occurs in your code. The user of your application is likely to be confused and frustrated when this happens. You can forestall many problems by including thorough error-handling routines in your code to handle any error that may occur.

When adding error handling to a procedure, you should consider how the procedure will route execution when an error occurs. The first step in routing execution to an error handler is to enable an error handler by including some form of the On Error statement within the procedure. The On Error statement directs execution in event of an error. If there’s no On Error statement, Visual Basic simply halts execution and displays an error message when an error occurs.

When an error occurs in a procedure with an enabled error handler, Visual Basic doesn’t display the normal error message. Instead it routes execution to an error handler, if one exists. When execution passes to an enabled error handler, that error handler becomes active. Within the active error handler, you can determine the type of error that occurred and address it in the manner that you choose. Access provides three objects that contain information about errors that have occurred, the ADO Error object, the Visual Basic Err object, and the DAO Error object.

Routing execution when an error occurs

An error handler specifies what happens within a procedure when an error occurs. For example, you may want the procedure to end if a certain error occurs, or you may want to correct the condition that caused the error and resume execution. The On Error and Resume statements determine how execution proceeds in the event of an error.

On Error statement

The On Error statement enables or disables an error-handling routine. If an error-handling routine is enabled, execution passes to the error-handling routine when an error occurs.

There are three forms of the On Error statement: On Error GoTo label, On Error GoTo 0, and On Error Resume Next. The On Error GoTo label statement enables an error-handling routine, beginning with the line on which the statement is found. You should enable the error-handling routine before the first line at which an error could occur. When the error handler is active and an error occurs, execution passes to the line specified by the label argument.

The line specified by the label argument should be the beginning of the error-handling routine. For example, the following procedure specifies that if an error occurs, execution passes to the line labeled:

Function MayCauseAnError() 
    ' Enable error handler. 
    On Error GoTo Error_MayCauseAnError 
    .            ' Include code here that may generate error. 
    . 
    . 
 
Error_MayCauseAnError: 
    .            ' Include code here to handle error. 
    . 
    . 
End Function

The On Error GoTo 0 statement disables error handling within a procedure. It doesn’t specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0. If there’s no On Error GoTo 0 statement in your code, the error handler is automatically disabled when the procedure has run completely. The On Error GoTo 0 statement resets the properties of the Err object, having the same effect as the Clear method of the Err object.

The On Error Resume Next statement ignores the line that causes an error and routes execution to the line following the line that caused the error. Execution isn’t interrupted. Use the On Error Resume Next statement if you want to check the properties of the Err object immediately after a line at which you anticipate an error will occur, and handle the error within the procedure rather than in an error handler.

Resume statement

The Resume statement directs execution back to the body of the procedure from within an error-handling routine. You can include a Resume statement within an error-handling routine if you want execution to continue at a particular point in a procedure. However, a Resume statement isn’t necessary; you can also end the procedure after the error-handling routine.

There are three forms of the Resume statement. The Resume or Resume 0 statement returns execution to the line at which the error occurred. The Resume Next statement returns execution to the line immediately following the line at which the error occurred. The Resume label statement returns execution to the line specified by the label argument. The label argument must indicate either a line label or a line number.

You typically use the Resume or Resume 0 statement when the user must make a correction. For example, if you prompt the user for the name of a table to open, and the user enters the name of a table that doesn’t exist, you can prompt the user again and resume execution with the statement that caused the error.

You use the Resume Next statement when your code corrects for the error within an error handler, and you want to continue execution without rerunning the line that caused the error. You use the Resume label statement when you want to continue execution at another point in the procedure, specified by the label argument. For example, you might want to resume execution at an exit routine, as described in the following section.

Exiting a procedure

When you include an error-handling routine in a procedure, you should also include an exit routine, so that the error-handling routine will run only if an error occurs. You can specify an exit routine with a line label in the same way that you specify an error-handling routine.

For example, you can add an exit routine to the example in the previous section. If an error doesn’t occur, the exit routine runs after the body of the procedure. If an error occurs, then execution passes to the exit routine after the code in the error-handling routine has run. The exit routine contains an Exit statement.

Function MayCauseAnError() 
    ' Enable error handler. 
    On Error GoTo Error_MayCauseAnError 
    .            ' Include code here that may generate error. 
    . 
    . 
 
Exit_MayCauseAnError: 
    Exit Function 
 
Error_MayCauseAnError: 
    .            ' Include code to handle error. 
    . 
    . 
    ' Resume execution with exit routine to exit function. 
    Resume Exit_MayCauseAnError 
End Function

Handling errors in nested procedures

When an error occurs in a nested procedure that doesn’t have an enabled error handler, Visual Basic searches backward through the calls list for an enabled error handler in another procedure, rather than simply halting execution. This provides your code with an opportunity to correct the error within another procedure. For example, suppose Procedure A calls Procedure B, and Procedure B calls Procedure C. If an error occurs in Procedure C and there’s no enabled error handler, Visual Basic checks Procedure B, then Procedure A, for an enabled error handler. If one exists, execution passes to that error handler. If not, execution halts and an error message is displayed.

Visual Basic also searches backward through the calls list for an enabled error handler when an error occurs within an active error handler. You can force Visual Basic to search backward through the calls list by raising an error within an active error handler with the Raise method of the Err object. This is useful for handling errors that you don’t anticipate within an error handler. If an unanticipated error occurs, and you regenerate that error within the error handler, then execution passes back up the calls list to find another error handler, which may be set up to handle the error.

For example, suppose Procedure C has an enabled error handler, but the error handler doesn’t correct for the error that has occurred. Once the error handler has checked for all the errors that you’ve anticipated, it can regenerate the original error. Execution then passes back up the calls list to the error handler in Procedure B, if one exists, providing an opportunity for this error handler to correct the error. If no error handler exists in Procedure B, or if it fails to correct for the error and regenerates it again, then execution passes to the error handler in Procedure A, assuming one exists.

To illustrate this concept in another way, suppose that you have a nested procedure that includes error handling for a type mismatch error, an error which you’ve anticipated. At some point, a division-by-zero error, which you haven’t anticipated, occurs within Procedure C. If you’ve included a statement to regenerate the original error, then execution passes back up the calls list to another enabled error handler, if one exists. If you’ve corrected for a division-by-zero error in another procedure in the calls list, then the error will be corrected. If your code doesn’t regenerate the error, then the procedure continues to run without correcting the division-by-zero error. This in turn may cause other errors within the set of nested procedures.

In summary, Visual Basic searches back up the calls list for an enabled error handler if:

  • An error occurs in a procedure that doesn’t include an enabled error handler.

  • An error occurs within an active error handler. If you use the Raise method of the Err object to raise an error, you can force Visual Basic to search backward through the calls list for an enabled error handler.

Getting information about an error

After execution has passed to the error-handling routine, your code must determine which error has occurred and address it. Visual Basic and Access provide several language elements that you can use to get information about a specific error. Each is suited to different types of errors. Since errors can occur in different parts of your application, you need to determine which to use in your code based on what errors you expect.

The language elements available for error handling include:

  • Err object

  • ADO Error object and Errors collection

  • DAO Error object and Errors collection

  • AccessError method

  • Error event

Err object

The Err object is provided by Visual Basic. When a Visual Basic error occurs, information about that error is stored in the Err object. The Err object maintains information about only one error at a time. When a new error occurs, the Err object is updated to include information about that error instead.

To get information about a particular error, you can use the properties and methods of the Err object:

  • The Number property is the default property of the Err object; it returns the identifying number of the error that occurred.
  • The Err object’s Description property returns the descriptive string associated with a Visual Basic error.
  • The Clear method clears the current error information from the Err object.
  • The Raise method generates a specific error and populates the properties of the Err object with information about that error.

The following example shows how to use the Err object in a procedure that may cause a type mismatch error:

Function MayCauseAnError() 
    ' Declare constant to represent likely error. 
    Const conTypeMismatch As Integer = 13 
 
    On Error GoTo Error_MayCauseAnError 
        .            ' Include code here that may generate error. 
        . 
        . 
 
Exit_MayCauseAnError: 
    Exit Function 
 
Error_MayCauseAnError: 
    ' Check Err object properties. 
    If Err = conTypeMismatch Then 
        .            ' Include code to handle error. 
        . 
        . 
    Else 
        ' Regenerate original error. 
        Dim intErrNum As Integer 
        intErrNum = Err 
        Err.Clear 
        Err.Raise intErrNum 
    End If 
    ' Resume execution with exit routine to exit function. 
    Resume Exit_MayCauseAnError 
End Function

Note that in the preceding example, the Raise method is used to regenerate the original error. If an error other than a type mismatch error occurs, execution will be passed back up the calls list to another enabled error handler, if one exists.

The Err object provides you with all the information you need about Visual Basic errors. However, it doesn’t give you complete information about Access errors or Access database engine errors. Access and Data Access Objects (DAO)) provide additional language elements to assist you with those errors.

Error object and Errors collection

The Error object and Errors collection are provided by ADO and DAO. The Error object represents an ADO or DAO error. A single ADO or DAO operation may cause several errors, especially if you are performing DAO ODBC operations. Each error that occurs during a particular data access operation has an associated Error object. All the Error objects associated with a particular ADO or DAO operation are stored in the Errors collection, the lowest-level error being the first object in the collection and the highest-level error being the last object in the collection.

When a ADO or DAO error occurs, the Visual Basic Err object contains the error number for the first object in the Errors collection. To determine whether additional ADO or DAO errors have occurred, check the Errors collection. The values of the ADO Number or DAO Number properties and the ADO Description or DAO Description properties of the first Error object in the Errors collection should match the values of the Number and Description properties of the Visual Basic Err object.

AccessError method

Use the Raise method of the Err object to generate a Visual Basic error that hasn’t actually occurred and determine the descriptive string associated with that error. However, you can’t use the Raise method to generate a Access error, an ADO error, or a DAO error. To determine the descriptive string associated with an Access error, an ADO error, or a DAO error that hasn’t actually occurred, use the AccessError method.

Error event

Use the Error event to trap errors that occur on an Access form or report. For example, if a user tries to enter text in a field whose data type is Date/Time, the Error event occurs. If you add an Error event procedure to an Employees form, then try to enter a text value in the HireDate field, the Error event procedure runs.

The Error event procedure takes an integer argument, DataErr. When an Error event procedure runs, the DataErr argument contains the number of the Access error that occurred. Checking the value of the DataErr argument within the event procedure is the only way to determine the number of the error that occurred. The Err object isn’t populated with error information after the Error event occurs. Use the value of the DataErr argument together with the AccessError method to determine the number of the error and its descriptive string.

[!NOTE]
The Error statement and Error function are provided for backward compatibility only. When writing new code, use the Err and Error objects, the AccessError function, and the Error event for getting information about an error.

About the contributors

Link provided by Community Member Icon the UtterAccess community.

  • Handling Access Errors with VBA

UtterAccess is the premier Microsoft Access wiki and help forum.

See also

  • Access for developers forum
  • Access help on support.office.com
  • Access forums on UtterAccess
  • Access developer and VBA programming help center (FMS)
  • Access posts on StackOverflow

[!includeSupport and feedback]

Bye For Now

All good things must come to an end. After 15 years, over 8,000hrs invested, 69 YouTube videos and more than 950 posts here, I have decided to move on.

Wishing you all the very best while I reevaluate this site’s future.

If you have any of my demos/code you are welcome to continue to use them, but reposting any of my articles/downloads/code/demos/… is strictly forbidden!

Содержание

  • Памятка по ошибкам VBA
  • Обработка ошибок VBA
  • Заявление об ошибке VBA
  • VBA IsError
  • Если ошибка VBA
  • Типы ошибок VBA
  • Другие термины ошибок VBA
  • Обработка ошибок VBA в Access

Ошибки

ОписаниеКод VBAПри ошибке — код остановки и ошибка отображенияПри ошибке Перейти к 0При ошибке — пропустить ошибку и продолжить работуПри ошибке Возобновить ДалееПри ошибке — перейдите к строке кода [Ярлык]При ошибке Перейти к [ярлык]Сбрасывает (сбрасывает) ошибкуПри ошибке GoTo -1Показать номер ошибкиMsgBox Err.NumberПоказать описание ошибкиMsgBox Ошибка ОписаниеФункция для генерации собственной ошибкиErr.Raise

См. Другие «Шпаргалки» по VBA и бесплатные загрузки в формате PDF.

Обработка ошибок VBA

Обработка ошибок VBA относится к процессу прогнозирования, обнаружения и устранения ошибок времени выполнения VBA. Процесс обработки ошибок VBA происходит при написании кода до того, как на самом деле возникнут какие-либо ошибки.

Ошибки времени выполнения VBA — это ошибки, возникающие во время выполнения кода. Примеры ошибок времени выполнения включают:

  • Ссылка на несуществующую книгу, лист или другой объект
  • Неверные данные напр. ссылка на ячейку Excel, содержащую ошибку
  • Попытка разделить на ноль

Заявление об ошибке VBA

Большая часть обработки ошибок VBA выполняется с помощью О заявлении об ошибке. Оператор On Error сообщает VBA, что делать в случае возникновения ошибки. Есть три О сообщениях об ошибках:

  • При ошибке GoTo 0
  • При ошибке Возобновить Далее
  • При ошибке GoTo Линия

При ошибке GoTo 0

При ошибке GoTo 0 является настройкой VBA по умолчанию. Вы можете восстановить этот параметр по умолчанию, добавив следующую строку кода:

Когда возникает ошибка с При ошибке GoTo 0, VBA прекратит выполнение кода и отобразит стандартное окно сообщения об ошибке.

Часто вы добавляете При ошибке GoTo 0 после добавления При ошибке Возобновить Далее обработка ошибок (следующий раздел):

123456789 Sub ErrorGoTo0 ()При ошибке Возобновить ДалееActiveSheet.Shapes («Start_Button»). УдалитьПри ошибке GoTo 0’Запустить больше кодаКонец подписки

При ошибке Возобновить Далее

При ошибке Возобновить Далее сообщает VBA пропустить любые строки кода, содержащие ошибки, и перейти к следующей строке.

1 При ошибке Возобновить Далее

Примечание: При ошибке Возобновить Далее не исправляет ошибку и не устраняет ее иным образом. Он просто сообщает VBA действовать, как если бы строка кода, содержащая ошибку, не существовала. Неправильное использование При ошибке Возобновить Далее может привести к непредвиденным последствиям.

Прекрасное время для использования При ошибке Возобновить Далее при работе с объектами, которые могут существовать, а могут и не существовать. Например, вы хотите написать код, который удалит фигуру, но если вы запустите код, когда фигура уже удалена, VBA выдаст ошибку. Вместо этого вы можете использовать При ошибке Возобновить Далее чтобы сообщить VBA об удалении формы, если она существует.

123 При ошибке Возобновить ДалееActiveSheet.Shapes («Start_Button»). УдалитьПри ошибке GoTo 0

Обратите внимание, что мы добавили При ошибке GoTo 0 после строки кода, содержащей потенциальную ошибку. Это сбрасывает обработку ошибок.

В следующем разделе мы покажем вам, как проверить, возникла ли ошибка, используя Err.Number, предоставляя вам более расширенные возможности обработки ошибок…

Err.Number, Err.Clear и перехват ошибок

Вместо того, чтобы просто пропустить строку, содержащую ошибку, мы можем отловить ошибку, используя При ошибке Возобновить Далее а также Err.Number.

Err.Number возвращает номер ошибки, соответствующий типу обнаруженной ошибки. Если ошибки нет, Err.Number = 0.

Например, эта процедура вернет «11», потому что возникает ошибка Ошибка времени выполнения ’11’.

1234567 Sub ErrorNumber_ex ()При ошибке Возобновить ДалееActiveCell.Value = 2/0MsgBox Err.NumberКонец подписки

Обработка ошибок с помощью Err.Number

Истинная сила Err.Number заключается в способности определить, произошла ли ошибка (Err.Number 0). В приведенном ниже примере мы создали функцию, которая будет проверять, существует ли лист, с помощью Err.Number.

12345678910111213141516171819 Sub TestWS ()MsgBox DoesWSExist («тест»)Конец подпискиФункция DoesWSExist (wsName As String) As BooleanDim ws как рабочий листПри ошибке Возобновить ДалееУстановить ws = Sheets (wsName)’Если ошибка WS не существуетЕсли Err.Number 0, тоDoesWSExist = FalseЕщеDoesWSExist = TrueКонец, еслиПри ошибке GoTo -1Конечная функция

Примечание. Мы добавили При ошибке GoTo -1 до конца, который сбрасывает Err.Number в 0 (см. два раздела ниже).

С участием При ошибке Возобновить Далее а также Err.Number, вы можете воспроизвести «Попробуй поймать» функциональность других языков программирования.

При ошибке GoTo Линия

При ошибке GoTo Линия сообщает VBA «перейти» к помеченной строке кода при обнаружении ошибки. Вы объявляете оператор Go To следующим образом (где errHandler — это метка строки, к которой нужно перейти):

1 При ошибке GoTo errHandler

и создайте метку строки следующим образом:

Примечание. Это тот же ярлык, который вы использовали бы с обычным заявлением VBA GoTo.

Ниже мы продемонстрируем использование При ошибке GoTo Линия Выйти из процедуры.

При ошибке Выход из подпрограммы

Вы можете использовать On Error GoTo Line для выхода из подпрограммы при возникновении ошибки.

Вы можете сделать это, поместив метку строки обработчика ошибок в конце вашей процедуры:

12345678 Sub ErrGoToEnd ()При ошибке GoTo endProc’Некоторый кодendProc:Конец подписки

или используя команду Exit Sub:

123456789101112131415 Sub ErrGoToEnd ()При ошибке GoTo endProc’Некоторый кодПерейти Пропустить ВыходendProc:Выйти из подводной лодкиskipExit:Еще немного кодаКонец подписки

Err.Clear, при ошибке GoTo -1 и сброс Err.Number

После обработки ошибки обычно следует удалить ее, чтобы предотвратить проблемы с обработкой ошибок в будущем.

После возникновения ошибки, оба Err.Clear а также При ошибке GoTo -1 можно использовать для сброса Err.Number до 0. Но есть одно очень важное отличие: Err.Clear не сбрасывает саму ошибку, а только сбрасывает Err.Number.

Что это обозначает? С использованиемErr.Clear, вы не сможете изменить настройку обработки ошибок. Чтобы увидеть разницу, проверьте этот код и замените При ошибке GoTo -1 с участием Err.Clear:

123456789101112131415161718192021 Sub ErrExamples ()При ошибке GoTo errHandler:»Ошибка, определяемая приложением»Ошибка (13)Выйти из подводной лодкиerrHandler:’Очистить ошибкуПри ошибке GoTo -1При ошибке GoTo errHandler2:Ошибка «Несоответствие типа»Ошибка (1034)Выйти из подводной лодкиerrHandler2:Отладка.Ошибка печати ОписаниеКонец подписки

Обычно я рекомендую всегда использовать При ошибке GoTo -1, если у вас нет веской причины использовать Err.Clear вместо.

VBA при ошибке MsgBox

Вы также можете отобразить окно сообщения при ошибке. В этом примере будут отображаться разные окна сообщений в зависимости от того, где возникла ошибка:

12345678910111213141516171819202122232425262728 Sub ErrorMessageEx ()Dim errMsg как строкаПри ошибке GoTo errHandler’Этап 1errMsg = «Произошла ошибка на этапе копирования и вставки.»‘Err.Raise (11)’Этап 2errMsg = «Произошла ошибка на этапе проверки данных.»Err.Raise (11)’Этап 3errMsg = «Произошла ошибка на этапе построения прибылей и убытков и копирования.»Err.Raise (11)’Этап 4errMsg = «Произошла ошибка при попытке зарегистрировать импорт на странице настройки»Err.Raise (11)GoTo endProcerrHandler:MsgBox errMsgendProc:Конец подписки

Здесь вы должны заменить Err.Raise (11) своим реальным кодом.

VBA IsError

Другой способ обработки ошибок — проверить их с помощью функции VBA IsError. Функция IsError проверяет выражение на наличие ошибок, возвращая ИСТИНА или ЛОЖЬ в случае возникновения ошибки.

123 Sub IsErrorEx ()MsgBox IsError (Диапазон («a7»). Значение)Конец подписки

Если ошибка VBA

Вы также можете обрабатывать ошибки в VBA с помощью функции Excel IfError. Доступ к функции IfError должен осуществляться с помощью Класс WorksheetFunction:

1234567 Sub IfErrorEx ()Dim n As Longn = WorksheetFunction.IfError (Range («a10»). Value, 0)MsgBox nКонец подписки

Это выведет значение диапазона A10, если значение является ошибкой, вместо этого будет выведено 0.

Типы ошибок VBA

Ошибки времени выполнения

Как указано выше:

Ошибки времени выполнения VBA — это ошибки, возникающие во время выполнения кода. Примеры ошибок времени выполнения включают:

  • Ссылка на несуществующую книгу, лист или другой объект
  • Неверные данные напр. ссылка на ячейку Excel, содержащую ошибку
  • Попытка разделить на ноль

Вы можете «обработать ошибки» ошибок времени выполнения, используя описанные выше методы.

Ошибки синтаксиса

Ошибки синтаксиса VBA это ошибки при написании кода. Примеры синтаксических ошибок:

  • Неправильное написание
  • Отсутствие или неправильная пунктуация

Редактор VBA выделяет множество синтаксических ошибок красным цветом:

В редакторе VBA также есть опция «Автоматическая проверка синтаксиса»:

Когда этот флажок установлен, редактор VBA сгенерирует окно сообщения, предупреждающее вас об ошибках синтаксиса после ввода строки кода:

Лично меня это очень раздражает, и я отключил эту функцию.

Ошибки компиляции

Прежде чем пытаться запустить процедуру, VBA «скомпилирует» процедуру. Компиляция преобразует программу из исходного кода (который вы видите) в исполняемую форму (вы не видите).

Ошибки компиляции VBA — это ошибки, препятствующие компиляции кода.

Хорошим примером ошибки компиляции является отсутствие объявления переменной:

Другие примеры включают:

  • Для без Следующий
  • Выбирать без Конец Выбрать
  • Если без Конец, если
  • Вызов процедура этого не существует

Ошибки синтаксиса (предыдущий раздел) — это подмножество ошибок компиляции.

Отладка> Компиляция

Ошибки компиляции появятся при попытке запустить процедуру. Но в идеале вы должны выявить ошибки компиляции до попытки запустить процедуру.

Сделать это можно, скомпилировав проект заранее. Для этого перейдите в Отладка> Скомпилировать проект VBA.

Компилятор «перейдет» к первой ошибке. Как только вы исправите эту ошибку, снова скомпилируйте проект. Повторяйте, пока все ошибки не будут исправлены.

Вы можете сказать, что все ошибки исправлены, потому что Скомпилировать проект VBA будет неактивным:

Ошибка переполнения

В Ошибка переполнения VBA происходит, когда вы пытаетесь поместить значение в слишком большую переменную. Например, Целочисленные переменные может содержать только значения от -32 768 до 32 768. Если вы введете большее значение, вы получите ошибку переполнения:

Вместо этого вы должны использовать Длинная переменная для хранения большего числа.

Другие термины ошибок VBA

Ошибка перехвата VBA

В отличие от других языков программирования, в VBA нет Заявление о вылове. Однако вы можете воспроизвести оператор Catch, используя При ошибке Возобновить Далее а также Если Err.Number 0, то. Это описано выше в разделе Обработка ошибок с помощью Err.Number.

Ошибка игнорирования VBA

Чтобы игнорировать ошибки в VBA, просто используйте При ошибке Возобновить Далее утверждение:

1 При ошибке Возобновить Далее

Однако, как упоминалось выше, вы должны быть осторожны при использовании этого оператора, поскольку он не исправляет ошибку, он просто игнорирует строку кода, содержащую ошибку.

VBA Throw Error / Err.Raise

Чтобы устранить ошибку в VBA, вы используете Err.Raise метод.

Эта строка кода вызовет ошибку времени выполнения ’13’: Несоответствие типов:

Перехват ошибок VBA

Перехват ошибок VBA это просто еще один термин для обработки ошибок VBA.

Сообщение об ошибке VBA

А Сообщение об ошибке VBA выглядит так:

Когда вы нажмете «Отладка», вы увидите строку кода, которая выдает ошибку:

Обработка ошибок VBA в цикле

Лучший способ обработки ошибок в цикле — использовать При ошибке Возобновить Далее вместе с Err.Number чтобы определить, произошла ли ошибка (не забудьте использовать Err.Clear чтобы сбрасывать ошибку после каждого появления).

Пример ниже разделит два числа (столбец A на столбец B) и выведет результат в столбец C. В случае ошибки результатом будет 0.

12345678910111213141516 Подтест ()Тусклая ячейка как диапазонПри ошибке Возобновить ДалееДля каждой ячейки в диапазоне («a1: a10»)’Установить значение ячейкиcell.Offset (0, 2) .Value = cell.Value / cell.Offset (0, 1) .Value’Если Cell.Value — Error, то по умолчанию 0Если Err.Number 0, тоcell.Offset (0, 2) .Value = 0Err.ClearКонец, еслиСледующийКонец подписки

Обработка ошибок VBA в Access

Все приведенные выше примеры работают в Access VBA точно так же, как и в Excel VBA.

123456789101112131415161718 Функция DelRecord (от формы как)’эта функция используется для удаления записи в таблице из формыПри ошибке GoTo заканчиваетсяС frmЕсли .NewRecord Тогда.ОтменитьФункция выходаКонец, еслиКонец сС помощью frm.RecordsetClone.Bookmark = frm.Bookmark.Удалитьfrm.RequeryКонец сФункция выходаокончание:КонецКонечная функция

Обработка ошибок на этапе выполнения

Как
бы тщательно не проверялся код, на этапе
его выполнения неизбежно возникают
ошибки. Попытка деления на ноль – это
типичный пример ошибки времени выполнения.
В Access обработка ошибок выполняется с
помощью инструкции On Error. Имеется три
вида инструкций On Error:

  1. On Error GoTo Метка – осуществляет переход
    на строку с меткой (Метка) при возникновении
    произвольной ошибки на этапе выполнения.
    После обработки ошибки можно либо
    вызвать повторение той части кода, где
    произошла ошибка, либо проигнорировать
    ошибку и продолжить выполнение
    последующих инструкций. Для возвращения
    на строку с ошибкой используется
    ключевое слово Resume.

  2. On Error Resume Next – игнорирует ошибку и
    продолжает выполнение последующих
    инструкций.

  3. On Error GoTo 0 – отключает обработку ошибок.

После
обработки первой ошибки инструкция On
Error GoTo Метка продолжает выполняться для
всех последующих ошибок, пока не
закончится выполнение данной процедуры
либо обработка ошибок не будет явно
отключена инструкцией On Error GoTo 0. Если
нет обработки какой-то ошибки или
обработка выключена, то при возникновении
необработанной ошибки приложение сразу
же выдаст сообщение об ошибке и прекратит
работу.

Если
процедура обработки некоторого события
создается с помощью мастера, то он
автоматически дополняет процедуру
кодом обработки ошибок.

Private Sub
MyID_DblClick(Cancel As Integer)

On Error GoTo
Err_MyID_DblClick

Текст процедуры

Exit_MyID_DblClick:

Exit Sub

Err_MyID_DblClick:

MsgBox
Err.Description

Resume
Exit_MyID_DblClick

End Sub

Объект
Err содержит информацию об ошибках
выполнения и обычно используется вместе
со структурой Select Case, чтобы определить,
какое действие предпринять в зависимости
от кода ошибки.

Select Case Err

Case 58 To 76

Call FileError- процедура обработки ошибок
работы с файлами

Case 281 To 297

Call DDEError — процедура для обработки ошибок
DDE

Case 340 To 344

Call ArrayError — процедура
ошибок массивов

End
Select

Err=0
— отключение обработки необработанных
ошибок.

Работа с объектами и коллекциями

В VBA
можно работать с объектами и коллекциями
Access, библиотекой доступа к данным DAO
(Data Access Objects), библиотекой прямого доступа
к данным баз данных ODBC (ODBC Direct), библиотекой
доступа к данным ADO (ActiveX Data Objects) и другими
библиотеками. В Access, DAO и ADO все объекты
расположены внутри коллекций и доступны
в VBA. Каждый объект имеет свойства и
методы. Все библиотеки организованы в
виде иерархии объектов. Объекты имеют
коллекции (семейства) подчиненных
объектов и т.д. В Access имеется восемь
базовых объектов; их иерархия представлена
на Рис. 1.

Объекты ms Access:

  1. Application – активное приложение;

  2. Control – элемент управления;

  3. DoCmd – объект вызова макрокоманд в VBA
    коде;

  4. Form – открытая форма;

  5. Module – объект, ссылающийся на стандартные
    модули;

  6. Reference – объект, содержащий ссылки на
    объекты;

  7. Report – открытый отчет;

  8. Screen – ссылка на экран;

Названия
семейств формируются путем возведения
в множественное число названия
соответствующего объекта. В свою очередь
большинство объектов имеют присоединенные
коллекции свойств (Properties),
а формы и отчеты – коллекции разделов
и т.д. Так как все объекты в Access хранятся
внутри иерархически связанных коллекций,
то доступ к объекту на нижней ступени
иерархии можно получить, указав все
имена коллекций, разделенных точкой,
начиная от корневого объекта. Например,
Application.Forms(«Заказы»).Controls(0).Properties(0).
Большинство коллекций, к примеру,
коллекции форм и отчетов, являются
глобальными. Тогда к объекту этой
коллекции можно обращаться напрямую:
Forms(«Заказы») или Forms!Заказы.

Рис. 1. Иерархия объектов Access

Поскольку библиотека DAO всегда поставляется
с Access, рассмотрим ее
структуру и основные методы более
подробно (Рис. 2).

Возможно, вам также будет интересно:

  • Acad ошибка при запуске приложения 0xc000007b
  • Acad exe системная ошибка
  • Acad exe ошибка приложения
  • Ac4bfsp exe ошибка приложения 0xc000007b
  • Ac32bitappserver dll autocad ошибка 2337

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии