Коды ошибок в visual basic

Номер

Сообщение

Описание

3

Return
without GoSub

Оператор Return без GoSub

5

Invalid
procedure call

Неверный вызов процедуры

6

Overflow

Переполнение

7

Out of
memory

Недостаточно памяти

9

Subscript
out of range

Индекс вне заданного диапазона

10

This
array is fixed or temporarily locked

Этот массив имеет фиксированную длину или он временно
заблокирован

11

Division
by zero

Деление на ноль

13

Type mismatch

Несоответствие типа

14

Out of
string space

Не хватает памяти для строки

16

Expression
too complex

Выражение слишком сложное

17

Can’t
perform requested operation

Невозможно выполнить требуемую операцию

18

User
interrupt occurred

Произошло прерывание по команде пользователя

20

Resume
without error

Оператор Resume применен за пределами кода, отвечающего за
обработку ошибки

28

Out of
stack space

В стеке не хватает памяти

35

Sub,
Function or Property not defined

Процедура Sub, Function или Property не определена

47

Too many
DLL application clients

Слишком много приложений обращаются к DLL

48

Error in
loading DLL

Ошибка при загрузке DLL

49

Bad DLL
calling convention

Неверный вызов DLL

51

Internal
error

Внутренняя ошибка

52

Bad file
name or number

Неверное имя или номер файла

53

File not
found

Файл не найден

54

Bad file
mode

Неверный тип доступа

55

File
already open

Файл уже открыт

57

Device
I/O error

Ошибка устройства ввода/вывода

58

File
already exists

Файл уже существует

59

Bad
record length

Неверный размер записи

61

Disk full

Диск переполнен

62

Input
past end of file

Чтение файла невозможно, т.к. достигнут его конец

63

Bad
record number

Неверный номер записи

67

Too many
files

Слишком много файлов

68

Device unavailable

Устройство недоступно

70

Permission
denied

Доступ запрещен

71

Disk not
ready

Диск не готов

74

Can’t
rename with different drive

Нельзя переименовать файл со сменой носителя

75

Path/File
access error

Ошибка доступа к каталогу/файлу

76

Path not
found

Каталог не найден

91

Object
variable or With block variable not set

Переменная объекта или переменная блока With не задана

92

For loop
not initialized

Цикл For не инициализирован

93

Invalid
pattern string

Неверная маска

94

Invalid
use or Null

Неверное использование Null

97

Can’t
call Friend procedure on an object that is not an instance of the defining
class

Нельзя вызвать процедуру Friend, т.к. она не является
экземпляром класса

98

A
property or method call cannot include a reference to a private object,
either as an argument or as a return value

Обращение к свойству или методу не может включать ссылку
на локальный объект. Этот объект также не может быть аргументом или
возвращаемым значением

260

No timer
available

Ни один таймер не доступен

282

No
foreign application responded to a DDE initiate

Ни одно внешнее приложение не ответило на инициативу DDE

288

Destination
is busy

Адресат занят

290

Data is
wrong format

Неправильный формат данных

294

Invalid
DDE Link format

Неверный формат данных в DDE-диалоге

296

PasteLink
already performed on this control

PasteLink для этого элемента управления уже выполнен

297

Can’t set
LinkMode; invalid LinkTopic

Нельзя установить LinkMode; неправильный LinkTopic

298

System
DLL could not be loaded

Системная DLL
(библиотека) не может быть загружена

320

Can’t use
character device names in specified file names

Нельзя использовать имя устройства в определении имени
файла

321

Invalid
file format

Неверный формат файла

322

Can’t
create necessary temporary file

Не могу создать необходимый временный файл

325

Invalid
format in resource file

Неверный формат файла ресурсов

327

Data
value named not found

Значение не найдено

328

Illegal
parameter; can’t write arrays

Неверный параметр; не могу записать массив

335

Could not
access system registry

Доступ к системному реестру невозможен

336

ActiveX
component not correctly registered

Компонент ActiveX зарегистрирован неправильно

337

ActiveX
component not found

Компонент ActiveX не найден

338

ActiveX
component did not run correctly

Компонент ActiveX не может быть корректно выполнен

340

Control
array element ‘item’ doesn’t exist

Элемент управления ‘имя’ не найден

341

Invalid
control array index

Неверный индекс массива элементов управления

342

Not
enough room to allocate control array ‘item’

Недостаточно памяти для создания элемента управления ‘имя’

343

Object
not an array

Объект не является массивом

344

Must
specify index for object array

Необходимо указать индекс массива

345

Reached
limit: cannot create any more controls on this form

Достигнута верхняя граница: нельзя создать больше ни
одного элемента управления в этой форме

360

Object
already loaded

Объект уже загружен

361

Can’t
load or unload this object

Невозможно загрузить или выгрузить данный объект

363

ActiveX
control specified not found

Элемент управления ActiveX не найден

364

Object
was unload

Объект был выгружен

365

Unable to
unload within this context

Нет возможности в данном контексте произвести выгрузку

366

No MDI
form available to load

Форма, не определенная как MDI, не может быть загружена

368

The
specified file is out of date. This program requires a later version

Данный файл устарел. Эта программа требует более новой
версии

371

The
specified object can’t be used as an owner form for Show

Данный объект не может быть использован как родитель формы
для ее показа

380

Invalid
property value

Неверное значение свойства

381

Invalid
property-array index

Неверный индекс массива свойств

382

Property
Set can’t be executed at run time

Процедура установки свойства (Property Set) не может быть запущена
во время выполнения программы

383

Property
Set can’t be used with
а read-only property

Процедура установки свойства (Property Set) не может быть
использована для свойств, доступных только для чтения

385

Need
property-array index

Для массива свойств надо указать индекс

387

Property
Set not permitted

Процедура установки свойства (Property Set) не разрешена

389

Invalid key

Нажата неверная клавиша

393

Property
Get can’t be executed at run time

Процедура чтения свойства (Property Get) не поддерживается
во время выполнения программы

394

Property
Get can’t be executed on write-only property

Процедура чтения свойства (Property Get) не может быть
использована для свойств, доступных только для записи

396

‘Item’
property cannot be set within a page

Свойство ‘имя’ нельзя установить для страницы (объект
Printer)

400

Form
already displayed; can’t show modally

Форма уже отображена, ее нельзя отобразить как модальную

401

Can’t
show non-modal form when modal form is displayed

Немодальную форму нельзя отобразить одновременно с модальной

402

Must
close or hide topmost modal form first

Сначала необходимо закрыть верхнюю модальную форму

403

HDI forms
cannot be shown modally

MDI-формы не могут быть отображены как модальные

404

MDI child
forms cannot be shown modally

Дочерние MDI-формы не могут быть отображены модальными

419

Permission
to use object denied

Использование объекта запрещено

422

Property
not found

Свойство не найдено

423

Property
or method not found

Свойство или метод не найдены

424

Object required

Необходим объект

425

Invalid
object use

Неверное использование объекта

427

Invalid
object type; Menu control required

Неверный тип объекта; требуется элемент управления типа
Menu

429

ActiveX
component can’t create object or return reference to this object

Компонент ActiveX
не может создать объект или возвратить ссылку на этот объект

430

Class
doesn’t support Automation

Класс не поддерживает программирование объектов
(Automation)

432

File name
or class name not found during Automation operation

Имя файла или класса не найдено в процессе операции
программирования объектов (Automation)

438

Object
doesn’t support this property or method

Объект не поддерживает данное свойство или метод

440

Automation error

Ошибка программирования объектов (Automation)

442

Connection
to type library or object library for remote process has been lost

Связь с библиотекой типов или объектов для удаленного
процесса была утеряна

443

Automation
object doesn’t have a default value

Объект Automation
не имеет значения по умолчанию

444

Method not applicable in this context

Метод в этом контексте недоступен

445

Object doesn’t support this action

Объект не поддерживает эту команду

446

Object
doesn’t support named arguments

Объект не поддерживает указанные аргументы

447

Object doesn’t support current locale setting

Объект не поддерживает текущие национальные стандарты

448

Name argument not found

Именованный аргумент не найден

449

Argument
not optional or invalid property assignment

Аргумент обязателен или неверное
назначение свойства

450

Wrong
number of arguments

Неправильное количество аргументов

451

Object not a collection

Объект не является коллекцией

452

Invalid ordinal

Неверный порядковый номер

453

Specified DLL function not found

Указанная функция DLL не найдена

454

Code
resource not found

Код ресурса не найден

457

This key
is already associated with an element of this collection

Этот ключ уже ассоциирован с элементом этой коллекции

458

Variable
uses a type not supported in Visual Basic

Переменная использует тип, не поддерживаемый Visual Basic

459

This
component doesn’t support the set of events

Этот компонент не поддерживает установку событий

460

Invalid Clipboard format

Неверный формат Буфера обмена

461

Specified
format doesn’t match format of data

Данный формат не совпадает с форматом данных

462

The
remote server machine does not exist or is unavailable

Удаленная машина сервера не существует или недоступна

463

Class not
registered on local machine

Класс не зарегистрирован на локальной машине

480

Can’t create AutoRedraw image

Нельзя создать автоматически восстанавливаемое изображение

481

Invalid picture

Неверный рисунок

482

Printer error

Ошибка принтера

483

Printer driver does not support specified property

Драйвер принтера не поддерживает указанное свойство

484

Problem
getting printer information from the system. Make sure the printer is set up
correctly

Проблема при чтении информации принтером из системы.
Убедитесь, что принтер установлен правильно

485

Invalid
picture type

Неверный тип рисунка

486

Can’t
print form image to this type of printer

Нельзя распечатать изображение формы на принтере такого
типа

520

Can’t empty Clipboard

Нельзя очистить буфер обмена

521

Can’t open Clipboard

Нельзя открыть буфер обмена

735

Can’t save file to TEMP directory

Нельзя сохранить файл в каталоге TEMP

744

Search text not found

Исходный текст не найден

746

Replacements too long

Слишком длинная замена

Номер

Сообщение

Описание

2420

Syntax error in number

Число содержит синтаксическую ошибку

2421

Syntax error in date

Дата содержит синтаксическую ошибку

2422

Syntax error in string

Строка содержит синтаксическую ошибку

2423

Invalid use of ‘.’, ‘!’ or ‘( )’

Неверное использование ‘.’, ‘!’ или ‘( )’

2424

Unknown name

Неизвестное имя

2425

Unknown function name

Неизвестное имя функции

2427

Object has no value

Объект не имеет значения

2428

Invalid arguments used with domain function

Неверные аргументы статистической функции по подмножеству

2431

Syntax error(missing operator)

Синтаксическая ошибка (отсутствует оператор)

2433

Syntax error

Синтаксическая ошибка

2439

Wrong number of arguments used with function

Неверное число аргументов функции

2442

Invalid use of parentheses

Неверное использование скобок

2443

Invalid use of Is operator

Неверное использование оператора Is

2445

Expression too complex

Слишком сложное выражение

2446

Out of memory during calculation

Недостаточно памяти при вычислениях

2448

Can’t set value

Не удается задать значение

3001

Invalid argument

Ошибочный аргумент

3005

<Database name> isn’t a valid database name

Имя базы данных не является допустимым именем базы данных

3006

Database <name> is exclusively locked

Для базы данных <name> установлен монопольный доступ

3007

Can’t open library database <name>

Не удается открыть библиотечную базу данных <name>

3011

The Microsoft Jet database engine could not find the
object <name>. Make sure the object exists and that you spell its name
and the path name correctly

Объект <name> не найден ядром базы данных Microsoft
Jet. Проверьте существование объекта и правильность имени и пути

3012

Object <name> already exists

Объект <name> уже существует

3017

The size of a field is too long

Слишком большая длина поля

3021

No current record

Текущая запись отсутствует

3024

Couldn’t find file <name>

Не удается найти файл <name>

3025

Can’t open any moor

Открытие дополнительных файлов невозможно

3027

Can’t update. Database or object is read-only

Обновление невозможно. База данных или объект доступны
только для чтения

3036

Database has reached maximum size

Достигнут максимальный размер базы данных

3037

Can’t open any more tables or queries

Открытие дополнительных таблиц или запросов невозможно

3042

Out of MS-DOS file handles

Не хватает дескрипторов файлов MS-DOS

3043

Disk or network error

Дисковая или сетевая ошибка

3046

Couldn’t save; currently locked by another user

Сохранение невозможно; блокировка другим пользователем

3056

Couldn’t repair this database

Не удается восстановить эту базу данных

3107

Record(s) can’t be added; no insert permission or
<name>

Записи не могут быть добавлены; отсутствует разрешение на
вставку данных для объекта <name>

3108

Record(s) can’t be edited; no update permission or
<name>

Записи не могут быть изменены; отсутствует разрешение на
обновление данных для объекта <name>

3109

Record(s) can’t be deleted; no delete permission or
<name>

Записи не могут быть удалены; отсутствует разрешение на
удаление данных для объекта <name>

3111

Couldn’t create; no modify design permission for table or
query <name>

Создание невозможно; отсутствует разрешение на изменение
макета для таблицы или запроса <name>

3117

Can’t sort on Memo or OLE Object <clause>

Невозможна сортировка по полю Memo или объекта ActiveX в
<clause>

3116

Can’t join on Memo or OLE Object <name>

Невозможно объединение с полем Memo или объекта ActiveX
<name>

3146

ODBC – call failed

ODBC – ошибка вызова

3154

ODBC – couldn’t find DLL <name>

ODBC – не удается найти DLL <name>

3197

The Microsoft Jet database engine stopped the process
because you and another user are attempting to change the same data at the
same time

Процесс остановлен ядром базы данных Microsoft Jet, так
как другой пользователь пытается одновременно изменить те же данные

3230

Out-of-date Paradox lock file

Устаревший файл блокировок Paradox

3231

ODBC – field would be too long; data truncated

ODBC – слишком большое поле; произошло усечение данных

3232

ODBC – couldn’t create table

ODBC – создание таблицы невозможно

3235

ODBC – data type not supported on server

ODBC – тип данных не поддерживается сервером

3238

ODBC – data out of range

ODBC – данные выходят за пределы допустимого диапазона

3276

Invalid database object reference

Неверная ссылка на объект Database

3322

Crosstab query contains one or more invalid fixed column
headings

Перекрестный запрос содержит один или несколько неверных
заголовков столбцов

3342

Invalid Memo or OLE Object in sub-query<name>

Ошибочное поле Memo или поле объекта ActiveX в подчиненном
запросе <name>

3360

Query is too complex

Слишком сложный запрос

3409

Invalid field name<name> in definition of index or
relationship

Неверное имя поля <name> при определении индекса или
связи

3411

Invalid entry. Can’t perform cascading operation in
table<name> because the value entered is too large for field
<name>

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

3423

You cannot use ODBC to import from, export to, or link an
external Microsoft Jet or ISAM database table to your database

Не допускается использование ODBC для импорта, экспорта
или присоединения таблицы из внешней базы данных Microsoft Jet или базы
данных ISAM

3424

Can’t create database because the locale is invalid

Создание базы данных невозможно; неверная национальная
настройка

3436

Failure creating file

Ошибка при создании, файла

3462

Failure to load DLL

Сбой при загрузке библиотеки

3506

The Synchronizer is unable to open the Synchronizer log

Синхронизатору не удается открыть журнал

3507

Failure writing to the Synchronizer log

Сбой при записи в журнал синхронизатора

3517

Synchronizer could not find any messages to process

Синхронизатор не может найти сообщение для обработки

3519

Failed to send a message

Сбой при отправке сообщения

3558

Disk I/O error at destination dropbox folder

Ошибка ввода/вывода на диске для результирующего банка
данных

3581

Can’t open replication system table <name> because
the table is already in use

Невозможно открыть системную таблицу репликации
<name>, так как она уже используется

3584

Insufficient memory to complete operation

Не хватает памяти для завершения операции

3586

Syntax
error in partial filter expression

Ошибка синтаксиса в выражении фильтра для таблицы
<name> в частичной реплике

3613

Can’t
create a relationship on linked ODBC tables

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

3614

GUID not allowed in Find method criteria expression

Не допускается использование типа GUID в выражениях для
условия поиска в методах Find

3621

Can’t change password on a shared open database

Невозможно изменение пароля базы данных, открытой для
общего доступа

3624

Couldn’t read the record; currently locked by another user

Чтение невозможно. Блокировка другим сеансом на данной
машине

3637

Cannot use the crosstab of as a non-fixed column a
subquery

Нельзя использовать составной или нефиксированный столбец
в качестве вторичного запроса

Contains a searchable list of common (core) VBA error codes used by the intrinsic Err object, as well as a separate list of all other errors.

When an error is generated in your application—whether it’s handled or not—the properties of the  Err object are assigned values with information about the error that just occurred. You can access this information, or generate your own errors explicitly using the Err.Raise method.

Err.Raise Number, [Source], [Description], [HelpFile], [HelpContext]

This, of course, requires knowledge of the error codes understood by the Err object. These are listed in searchable tables below (with hyperlinks to associated MSDN pages where available) . Error codes and descriptions were obtained from the following sources:

  • Core Visual Basic Language Errors
  • Miscellaneous Visual Basic Errors
  • ActiveX Control Errors

You can also define your own errors to unify the error-handling process. For example, see the article: Organizing Unstructured Errors in VBA.

Add the vbObjectError constant to custom error codes to guaranteed that the resulting number is not already in use.

Common VBA Error Codes

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

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]

№ На английском языке На русском языке 3 Return without GoSub Инструкция Return без GoSub 5 Invalid procedure call Недопустимый вызов процедуры 6 Overflow Переполнение 7 Out of memory Недостаточно памяти 9 Subscript out of range Индекс вне заданного диапазона 10 This array is fixed or temporarily locked Этот массив имеет фиксированную длину или он временно заблокирован 11 Division by zero Деление на 0 13 Type mismatch Несоответствие типа 14 Out of string space Недостаточно памяти для строки 16 Expression too complex Выражение слишком сложное 17 Can’t perform requested operation Невозможно выполнить требуемую операцию 18 User interrupt occurred Выполнение прервано пользователем. 20 Resume without error Оператор Resume применен за пределами кода, отвечающего за обработку ошибки 28 Out of stack space В стеке не хватает памяти 35 Sub, Function, or Property not defined Процедура типа Sub, Function или Property не определена 47 Too many DLL application clients Слишком много приложений обращаются к DLL 48 Error in loading DLL Ошибка при загрузке DLL 49 Bad DLL calling convention Неправильное соглашение о вызове DLL 51 Internal error Внутренняя ошибка 52 Bad file name or number Неправильное имя или номер файла 53 File not found Файл не найден 54 Bad file mode Неправильный режим файла 55 File already open Файл уже открыт 57 Device I/O error Ошибка устройства ввода/вывода 58 File already exists Файл уже существует 59 Bad record length Неправильная длина записи 61 Disk ftill Переполнение диска 62 Input past end of file Ввод за меткой конца файла 63 Bad record number Неправильный номер записи 67 Too many files Слишком много файлов 68 Device unavailable Устройство недоступно 70 Permission denied Доступ запрещен 71 Disk not ready Диск не готов 74 Can’t rename with different drive Невозможно переименование с другим именем диска файл 75 Path/File access error Ошибка при доступе файлу/каталогу 76 Path not found Путь определен неверно 91 Object variable or With block variable not set Переменная объекта или переменная блока With не задана 92 For loop not initialized Цикл For не инициализирован 93 Invalid pattern string Неправильный шаблон строки 94 Invalid use of Null Недопустимое использование Null 260 No timer available Ни один таймер недоступен 282 No foreign application responded to a DDE initiate Ни одно внешнее приложение не ответило на инициативу DDE 285 Foreign application won’t perform DDE method or operation Внешнее приложение не может выполнить метод или операцию DDE 286 Timeout while waiting for DDE response Простой при ожидании ответа DDE 287 User pressed Escape key during DDE ope ratio Во время операции DDE пользователь нажал клавишу [Esc] 288 Destination is busy Адресат занят 290 Data in wrong format Неправильный формат данных 293 DDE Method invoked with no channel open Метод DDE вызван без открытого канала 294 Invalid DDE Link format Недопустимый формат данных в DDE-диалоге 296 PasteLink already performed on this control PasteLink для этого элемента управления уже выполнен 297 «Can’t set LinkMode; invalid LinkTopic» «Нельзя установить LinkMode; неправильный LinkTopic» 298 System DLL ‘dll’ could not be loaded Системная DLL не может быть загружена 320 Can’t use character device names in specified file names Нельзя использовать имя устройства в определении имени файла 321 Invalid file format Недопустимый формат файла 325 Invalid format in resource file Недопустимый формат файла ресурсов 326 Resource with identifier ‘item’ not found Ресурс с идентификатором ‘имя’ не найден 335 Could not access system registry Доступ к системному реестру невозможен 336 ActiveX component not correctly registered Компонент ActiveX зарегистрирован неправильно 337 ActiveX component not found Компонент ActiveX не найден 338 ActiveX component did not run correctly Компонент ActiveX не может быть корректно выполнен 340 Control array element ‘item’ doesn’t exist Элемент управления ‘имя’ не найден 341 Invalid control array index Недопустимый индекс массива элементов управления 342 Not enough room to allocate control array ‘item’ Недостаточно памяти для создания элемента управления ‘имя’ 343 Object not an array Объект не является массивом 344 Must specify index for object array Необходимо указать индекс массива объектов 345 Reached limit: cannot create any more controls on this form Достигнута верхняя граница: нельзя создать больше ни одного элемента управления в этой форме 360 Object already loaded Объект уже загружен 361 Can’t load or unload this object Невозможно загрузить или выгрузить данный объект 362 Can’t unload controls created at design time Нельзя выгрузить элементы управления 363 ActiveX control specified not found Элемент управления ActiveX не найден 364 Object was unloaded Объект был выгружен 365 Unable to unload within this context Нет возможности в данном контексте произвести выгрузку 366 No MDI form available to load Форма, не определенная как MDI, не может быть загружена 380 Invalid property value Недопустимое значение свойства 381 Invalid property-array index Недопустимый индекс массива свойств 382 Property Set can’t be executed at : time Инструкция Property Set не может использоваться во время выполнения 383 Property Set can’t be used with a read-only property Инструкция Property Set не поддерживается (свойство доступно только для чтения) 384 A form can’t be moved or sized while minimized or maximized Если форма максимизирована или минимизирована, ее нельзя переместить или изменить ее размер 385 Need property-array index Для массива свойств надо указать индекс 387 Property Set not permitted Применение Property Set не разрешено 388 Can’t set Visible property from a parent menu Для команды подменю нельзя установить свойство Visible из программного кода, относящегося к обработке команд родительского меню 389 Invalid key Нажата недопустимая клавиша 393 Property Get can’t be executed at run time Инструкция Property Get не поддерживается во время выполнения 394 Property Get can’t be executed on write- only property Инструкция Property Get не поддерживается (свойство доступно только для записи) 395 Cannot use separator bar as menu name for this Разделительная линия не может использоваться как имя команды меню 396 ‘Item’ property cannot be set within a page Свойство ‘имя’ нельзя установить для страницы (объект Printer) 397 Can’t load, unload, or set Visible property for top level menus while they are merged Свойство Visible нельзя устанавливать пока элемент управления типа меню находится в контейнере формы 400 «Form already displayed; can’t show modally» Форма уже отображена, ее нельзя отобразить как модальную 401 Can’t show non-modal form when modal form is displayed Немодальную форму нельзя отобразить одновременно с модальной 402 Must close or hide topmost modal form first Сначала необходимо закрыть верхнюю модальную форму 403 MDI forms cannot be shown modally MDI-формы не могут быть отображены как модальные 404 MDI child forms cannot be shown modally Дочерние MDI-формы формы не мо- гут быть отображены модальными 419 Permission to use object denied Использование объекта запрещено 423 Property or method not found Свойство или метод не найдены 424 Object required Требуется объект 426 Only one MDI Form allowed Допустима только одна форма MDI 427 «Invalid object type; Menu control required» «Недопустимый тип объекта; требуется элемент управления типа «»меню» 428 Popup menu must have at least one submenu Всплывающее меню должно иметь хотя бы один элемент 429 ActiveX component can’t create object or return reference to this object Невозможно создание объекта или возвращение ссылки на этот объект компонентом ActiveX 430 Class doesn’t support Automation Класс не поддерживает программирование объектов 432 File name or class name not found during Automation operation Не найдено имя файла или класса при программировании объектов 438 Object doesn’t support this property or method Объект не поддерживает это свойство или метод 440 Automation error Ошибка программирования объектов 443 Automation object doesn’t have a default value Программируемый объект не имеет значения по умолчанию 444 Method not applicable in this context Метод в этом контексте недоступен 445 Object doesn’t support this action Эта команда не поддерживается указанным объектом 446 Object doesn’t support named arguments Именованные аргументы не поддерживаются указанным объектом 447 Object doesn’t support current locale setting Объект не поддерживает текущие национальные стандарты 448 Named argument not found Именованный аргумент не найден 449 Argument not optional Аргумент обязателен 450 Wrong number of arguments Неправильное количество аргументов 451 Object not a collection Объект не является коллекцией 452 Invalid ordinal Недопустимый порядковый номер 453 Specified DLL function not found Указанная функция DLL не найдена 457 This key is already associated with an element of this collection Запись уже связана с элементом данной коллекции 460 Invalid Clipboard format Недопустимый формат буфера обмена 461 Specified format doesn’t match format of data Указанный формат не соответствует формату данных 480 Can’t create AutoRedraw image Нельзя создать автоматически восстанавливаемое изображение 481 Invalid picture Недопустимый рисунок 482 Printer error Ошибка принтера 483 Printer driver does not support specified property Драйвер принтера не поддерживает указанное свойство 484 Problem getting printer information from the system. Make sure the printer is set up correctly Проблемы с получением системной информации. Проверьте правильность установок принтера 485 Invalid picture type Недопустимый тип рисунка 520 Can’t empty Clipboard Нельзя очистить буфер обмена 521 Can’t open Clipboard Нельзя открыть буфер обмена 2420 Syntax error in number Число содержит синтаксическую ошибку 2421 Syntax error in date Дата содержит синтаксическую ошибку 2422 Syntax error in string Строка содержит синтаксическую ошибку 2423 Invalid use of’.’, ‘!’, or ‘()’ Недопустимое использование ‘.’, ‘!’ или ‘()’ 2424 Unknown name Неизвестное имя 2425 Unknown function name Неизвестное имя функции 2426 Function isn’t available in expressions Функция недоступна в выражениях 2427 Object has no value Объект не имеет значения 2428 Invalid arguments used with domain function Недопустимые аргументы статистической функции по подмножеству 2429 In operator without () Оператор In требует наличия скобок: () 2430 Between operator without And За оператором Between отсутствует оператор And 2431 Syntax error (missing operator) Ошибка синтаксиса (отсутствует оператор) 2432 Syntax error (comma) Ошибка синтаксиса (запятая) 2433 Syntax error Ошибка синтаксиса 2434 Syntax error (missing operator) Ошибка синтаксиса (отсутствует оператор) 2435 Extra ) Непарная правая скобка: ) 2436 Missing ), ], or Item Отсутствует ), ] или элемент 2437 Invalid use of vertical bars Недопустимое использование символов вертикальной черты 2438 Syntax error Ошибка синтаксиса 2439 Wrong number of arguments used with function Неверное число аргументов функции 2440 IIF function without () Требуются скобки после функции IIF:() 2442 Invalid use of parentheses Недопустимое использование скобок 2443 Invalid use of Is operator Недопустимое использование оператора Is 2445 Expression too complex Слишком сложное выражение 2446 Out of memory during calculation Недостаточно памяти при вычислениях 2447 Invalid use of’.’, ‘!’, or ‘()’ Недопустимое использование ‘.’, ‘!’ или ‘()’ 2448 Can’t set value Не удается задать значение 3000 «Reserved error <Item>;» Зарезервированная ошибка элемента 3001 Invalid argument Ошибочный аргумент 3002 Couldn’t start session Запуск сеанса невозможен 3003 «Couldn’t start transaction;» Транзакция не может быть запущена 3005 < Database name> isn’t a valid database name Имя базы данных не является допустимым именем базы данных 3006 Database <name> is exclusively locked Для базы данных <name> установлен монопольный доступ 3007 Can’t open library database <name> Не удается открыть библиотечную базу данных <name> 3008 The table <name> is already opened exclusively by another user, or it is already open through the user interface and cannot be manipulated program Таблица <name> уже открыта другим пользователем для монопольного доступа или открыта в интерактивном режиме и не может быть изменена в программе 3009 You tried to lock a table while opening it, but the table can’t be locked because it is currently in use. Wait a moment, and then try the operation again «Не удается блокировать таблицу<name> при открытии; она в данное время используется. Подождите немного и повторите операцию» 3010 Table <name> already exists Таблица <name> уже существует 3011 The Microsoft Jet database engine could not find the object <name>. Make sure the object exists and that you spell its name and the path name correctly Объект <name> не найден ядром базы данных Microsoft Jet. Проверьте существование объекта и правильность имени и пути 3012 Object <name> already exists Объект <name> уже существует 3013 Couldn’t rename installable ISAM file Не удается переименовать файл устанавливаемого драйвера ISAM 3014 Can’t open any more tables Открытие большего числа таблиц невозможно 3015 <Index name > isn’t an index in this table. Look in the Indexes collection of the TableDef object to determine the valid index names <Index name > не является индексом данной таблицы. Для определения допустимых имен индексов просмотрите семейство Indexes объекта TableDef 3016 Field won’t fit in record Поле не помещается в записи 3017 The size of a field is too long Слишком большая длина поля 3018 Couldn’t find field <name> Не удается найти поле <name> 3019 Operation invalid without a current index Недопустимая операция без текущего индекса 3020 Update or CancelUpdate without Попытка вызвать метод Update или 3021 No current record Текущая запись отсутствует 3022 The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index Изменения не были успешно завершены из-за повторяющихся значений в индексе, ключевых полях или связях. Измените, данные в поле или полях, содержащих повторяющиеся значения, удалите индекс или переопределите его, чтобы разрешить повторяющиеся значения 3023 AddNew or Edit already used Методы AddNew или Edit уже используются 3024 Couldn’t find file <name> Не удается найти файл <name> 3025 Can’t open any more files Открытие дополнительных файлов невозможно 3026 Not enough space on disk Недостаточно места на диске 3027 Can’t update. Database or object is read-only Обновление невозможно. База данных или объект доступны только для чтения 3028 Can’t start your application. The workgroup information file is missing or opened exclusively by another user Не удается запустить приложение. Системная база данных отсутствует или открыта с монопольным доступом другим пользователем 3029 Not a valid account name or password Недопустимое имя учетной записи или пароль 3030 <Account name> isn’t a valid account name <Account name> не является допустимым именем учетной записи 3031 Not a valid password Неверный пароль 3032 Can’t perform this operation Невозможно выполнение данной операции. 3033 You don’t have the necessary permissions to use the <name> object. Have your system administrator or the person who created this object establish the appropriate permissions for you Отсутствуют разрешения на использование объекта <name>. Необходимые разрешения должны быть предоставлены системным администратором или пользователем, создавшим объект 3034 You tried to commit or roll back a transaction without first using Begin- Trans Попытка занесения или свертывания транзакции без предварительного вызова BeginTrans 3036 Database has reached maximum size Достигнут максимальный размер базы данных 3037 Can’t open any more tables or queries Открытие дополнительных таблиц или запросов невозможно 3039 «Couldn’t create index; too many indexes already defined» «Не удается создать индекс; уже определено слишком много индексов» 3040 Disk I/O error during read Ошибка ввода/вывода при чтении диска 3041 Can’t open a database created with a previous version of your application Не удается открыть базу данных, созданную в предыдущей версии приложения 3042 Out of MS-DOS file handles Не хватает дескрипторов файлов MS-DOS 3043 Disk or network error Дисковая или сетевая ошибка 3044 <Path> isn’t a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides Строка <Path> задает ошибочный путь. Проверьте, что путь задан правильно и имеется подключение к серверу, на котором находятся файлы 3045 «Couldn’t use <name>; file already in use» «Невозможно использовать <name>; файл уже используется» 3046 «Couldn’t save; currently locked by another user» «Сохранение невозможно; блокировка другим пользователем» 3047 Record is too large Слишком большая длина записи 3048 Can’t open any more databases Открытие дополнительных баз данных невозможно 3049 Can’t open database <name>. It may not be a database that your application recognizes, or the file may be corrupt Открытие базы данных <name> невозможно. Вероятно, это не база данных приложения пользователя, или ее файл поврежден 3051 The Microsoft Jet database engine cannot open the file <name>. It is already opened exclusively by another user, or you need permission to view its data Файл <name> не может быть открыт ядром базы данных Microsoft Jet. Файл уже открыт другим пользователем для монопольного доступа или требуется разрешение на просмотр данных 3052 MS-DOS file sharing lock count exceeded. You need to increase the number of locks installed with SHARE.EXE Достигнуто максимальное число блокировок файлов общего доступа MS- DOS. Необходимо увеличить число блокировок, установленных при запуске файла SHARE.EXE 3053 Too many client tasks Запущено слишком много задач- клиентов 3054 Too many Memo or OLE Object fields Слишком много полей Memo или объектов ActiveX 3055 Not a valid file name Недопустимое имя файла 3056 Couldn’t repair this database Не удается восстановить эту базу данных 3057 Operation not supported on linked tables Невозможно выполнение данной операции для присоединенных или связанных таблиц 3058 Index or primary key can’t contain a Null value Индекс или ключ не может содержать пустое значение (Null) 3059 Operation canceled by user Операция прервана пользователем 3060 Wrong data type for parameter<parameter> Недопустимый тип данных для параметра <parameter> 3061 Too few parameters. Expected <number> Слишком мало параметров. Требуется <number> 3062 Duplicate output alias <name> Повторение выходного псевдонима<name> 3063 Duplicate output destination <name> Повторение получателя <name> 3064 Can’t open action query <name> Не удается открыть запрос на изменение <name> 3065 Can’t execute a select query Невозможен запуск запроса на выборку 3066 Query must have at least one destination field Запрос должен иметь хотя бы одно поле для вывода 3067 Query input must contain at least one table or query В качестве входных данных запрос должен иметь хотя бы одну таблицу или запрос 3068 Not a valid alias name Недопустимое имя псевдонима 3069 The action query <name> cannot be used as a row source Не допускается применение запроса на изменение <name> в качестве источника строк 3070 The Microsoft Jet database engine does not recognize <name> as a valid field name or expression <name> не распознается ядром базы данных Microsoft Jet как допустимое имя поля или выражение 3071 This expression is typed incorrectly, or it is too complex to be evaluated. For example, a numeric expression may contain too many complicated elements. Try simplifying the expression by assigning parts of the expression to variables Выражение неверно введено или является слишком сложным для расчета. Например, числовое выражение может содержать слишком много элементов. Попытайтесь упростить выражение, определив его части как переменные 3073 Operation must use an updatable query В операции должен использоваться обновляемый запрос 3074 Can’t repeat table name <name> in FROM clause Невозможно повторение имени таблицы <name> в предложении FROM 3075 <Message> in query expression<expression> <Message> в выражении запроса<expression> 3076 <Name> in criteria expression <Name> в выражении для условия отбора 3077 <Message> in expression <Message> в выражении 3078 The Microsoft Jet database engine cannot find the input table or query<name>. Make sure it exists and that its name is spelled correctly Ядро базы данных Microsoft Jet не может найти входную таблицу или запрос <name>. Проверьте существование таблицы или запроса и правильность имени 3079 The specified field reference could refer to more than one table listed in the FROM clause of your SQL statement Ссылка на поле <пате> может относиться к полям нескольких таблиц, перечисленных в предложении FROM инструкции SQL 3080 Joined table <name> not listed in FROM clause Связанная таблица <name> отсутствует в предложении FROM 3081 Can’t join more than one table with the same name <name> Объединение не может содержать несколько таблиц с одинаковым именем <name> 3082 JOIN operation <operation> refers to a field that isn’t in one of the joined tables Операция JOIN <operation> содержит ссылку на несвязанную таблицу 3083 Can’t use internal report query Невозможно использование внутреннего запроса отчета 3084 Can’t insert data with action query Невозможно добавление данных с помощью запроса на изменение 3085 Undefined function <name> in expression Неопределенная функция <name> в выражении 3086 Couldn’t delete from specified tables Невозможно удаление записей из указанных таблиц 3087 Too many expressions in GROUP BY clause Слишком много выражений в предложении GROUP BY 3088 Too many expressions in ORDER BY clause Слишком много выражении в предложении ORDER BY 3089 Too many expressions in DISTINCT output Слишком много выражении в предложении DISTINCT 3090 Resultant table not allowed to have more than one AutoNumber field Результирующая таблица не должна иметь более одного поля счетчика 3092 Can’t use HAVING clause in TRANSFORM statement Нельзя использовать предложение HAVING в инструкции TRANS- FORM 3093 ORDER BY clause <clause> conflicts with DISTINCT Предложение ORDER BY <clause> конфликтует с DISTINCT 3094 ORDER BY clause <clause> conflicts with GROUP BY clause Предложение ORDER BY <clause> конфликтует с предложением GROUP BY 3095 Can’t have aggregate function in expression <expression> Невозможно использование статистической функции в выражении<expression> 3096 Can’t have aggregate function in WHERE clause <clause> Невозможно использование статистической функции в предложении WHERE <clause> 3097 Can’t have aggregate function in ORDER BY clause <clause> Невозможно использование статистической функции в предложении ORDER BY <clause> 3098 Can’t have aggregate function in GROUP BY clause <clause> Невозможно использование статистической функции в предложении GROUP BY <clause> 3099 Can’t have aggregate function in JOIN operation <operation> Невозможно использование статистической функции в операции JOIN <operation> 3100 Can’t set field <name> in join key to Null Для поля ключа связи <name> невозможно задание значения Null 3101 The Microsoft Jet database engine can’t find a record in the table <name> with key matching field(s) <name> В таблице <name> ядром базы данных Microsoft Jet не найдены записи с совпадающим ключевым полем<name> 3102 Circular reference caused by <query reference> Циклическая ссылка, связанная с<query reference> 3103 Circular reference caused by alias<name> in query definition’s SELECT list Псевдоним <name> из списка определений SELECT запроса привел к возникновению циклической ссылки 3104 Can’t specify fixed column heading<value> in a crosstab query more than once Невозможно более одного раза задать заголовок столбца <value> перекрестного запроса 3105 Missing destination field name in SELECT INTO statement <statement> В инструкции SELECT INTO <statement> пропущено имя результирующего поля 3106 Missing destination field name in UPDATE statement <statement> В инструкции UPDATE <statement пропущено имя результирующего поля 3107 «Record(s) can’t be added; no insert permission on <name>» «Записи не могут быть добавлены; отсутствует разрешение на вставку данных для объекта <name>» 3108 «Record(s) can’t be edited; no update permission on <name>» «Записи не могут быть изменены; отсутствует разрешение на обновление данных для объекта <name>» 3109 «Record(s) can’t be deleted; no delete permission on <name>» «Записи не могут быть удалены; отсутствует разрешение на удаление данных для объекта <name>» 3110 «Couldn’t read definitions; no read definitions permission for table or query<name>» «Не удается прочитать описания; отсутствует разрешение на чтение описания для объекта <name>» 3111 «Couldn’t create; no modify design permission for table or query <name>» «Создание невозможно; отсутствует разрешение на изменение макета для таблицы или запроса <name>» 3112 «Record(s) can’t be read; no read permission on <name>» «Записи не могут быть прочитаны; отсутствует разрешение на чтение данных для <name>» 3113 «Can’t update <field name>; field not updatable» «Невозможно обновить поле <field name>; не обновляемое поле» 3114 Can’t include Memo or OLE Object when you select unique values <statement> При отборе уникальных значений в<statement> нельзя использовать поле Memo или объекта ActiveX 3115 Can’t have Memo or OLE Object fields in aggregate aigument <statement> Поле Memo или объекта ActiveX не может присутствовать в аргументе статистической функции в <statement> 3116 Can’t have Memo or OLE Object fields in criteria <criteria> for aggregate function Поле Memo или объекта ActiveX не может присутствовать в условии отбора <criteria> для статистической функции 3117 Can’t sort on Memo or OLE Object<clause> Невозможна сортировка по полю Memo или объекта ActiveX в <clause> 3118 Can’t join on Memo or OLE Object<name> Невозможно объединение с полем Memo или объекта ActiveX <name> 3119 Can’t group on Memo or OLE Object<clause> Невозможна группировка по полю Memo или объекта ActiveX в <clause> 3120 Can’t group on fields selected with ‘*'»table name» Невозможна группировка по полям, выбранным с помощью символа ‘*'<table name> 3121 Can’t group on fields selected with ‘*’ Невозможна группировка по полям, выбранным с помощью символа ‘*’ 3122 You tried to execute a query that doesn’t include the specified expression <name> as part of an aggregate function Попытка выполнить запрос, который не включает указанное выражение <name> как часть статистической функции или группы 3123 Can’t use ‘*’ in crosstab query Невозможно использование символа ‘*’ в перекрестном запросе 3124 Can’t input from internal report query<name> Невозможен ввод из внутреннего запроса отчета <name> 3125 The database engine can’t find <name>. Make sure it is a valid parameter or alias name, that it doesn’t include invalid characters or punctuation, and that the name isn’t too long <Name> не найдено ядром базы данных. Проверьте, что оно представляет допустимый параметр или псевдоним, не содержит недопустимые символы или знаки препинания, а также не является слишком длинным 3126 Invalid bracketing of name <name> Недопустимое использование скобок с именем <name> 3127 The INSERT INTO statement contains the following unknown field name: <field name>. Make sure you’ve typed the name correctly, and try the ope- ration again Инструкция INSERT INTO содержит неизвестное имя <field name>. Проверьте, что имя задано без ошибок, и повторите операцию 3128 Specify the table containing the records you want to delete Необходимо указать таблицу, содержащую удаляемые записи 3129 «Invalid SQL statement; expected DE- LETE, INSERT, PROCEDURE, SE- LECT, or UPDATE» «Ошибочная инструкция SQL; предполагалось DELETE, INSERT, PRO- CEDURE, SELECT или UPDATE» 3130 Syntax error in DELETE statement Ошибка синтаксиса в инструкции DELETE 3131 Syntax error in FROM clause Ошибка синтаксиса в предложении FROM 3132 Syntax error in GROUP BY clause Ошибка синтаксиса в предложении GROUP BY 3133 Syntax error in HAVING clause Ошибка синтаксиса в предложении HAVING 3134 Syntax error in INSERT INTO statement Ошибка синтаксиса в инструкции INSERT INTO 3135 Syntax error in JOIN operation Ошибка синтаксиса в операции JOIN 3136 The LEVEL clause includes a reserved word or argument that is misspelled or missing, or the punctuation is incorrect Ошибочное или пропущенное зарезервированное слово или аргумент в предложении LEVEL или неверная пунктуация 3138 Syntax error in ORDER BY clause Ошибка синтаксиса в предложении ORDER BY 3139 Syntax error in PARAMETER clause Ошибка синтаксиса в предложении PARAMETER 3140 Syntax error in PROCEDURE clause Ошибка синтаксиса в предложении PROCEDURE 3141 The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect Ошибочное или пропущенное зарезервированное слово или аргумент в инструкции SELECT или неверная пунктуация 3143 Syntax error in TRANSFORM statement Ошибка синтаксиса в инструкции TRANSFORM 3144 Syntax error in UPDATE statement Ошибка синтаксиса в инструкции UPDATE 3145 Syntax error in WHERE clause Ошибка синтаксиса в предложении WHERE 3146 ODBC — call failed ODBC — ошибка вызова 3151 ODBC — connection to <name> failed ODBC — ошибка подключения к<name> 3154 ODBC — couldn’t find DLL <name> ODBC — не удается найти DLL<name> 3155 ODBC — insert on a linked table failed ODBC — вставка для присоединенной (связанной) таблицы <name> не выполнена 3156 ODBC — delete on a linked table failed ODBC — удаление для присоединенной (связанной) таблицы не выполнено 3157 ODBC — update on a linked table failed ODBC — обновление для присоединенной (связанной) таблицы не выполнено 3158 «Couldn’t save record; currently locked by another user» «Сохранение записи невозможно; установлена блокировка другим пользователем» 3159 Not a valid bookmark Недопустимая закладка 3160 Table isn’t open Таблица не открыта 3161 Couldn’t decrypt file Не удается дешифровать файл 3162 You tried to assign the Null value to a variable that isn’t a Variant data type Попытка присвоить значение Null переменной, не принадлежащей к типу Variant 3163 The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data «Выполнение операции невозможно; объем данных велик для поля» 3164 The field can’t be updated because another user or process has locked the corresponding record or table Не удается обновить поле, поскольку соответствующая запись или таблица блокирована другим пользователем или процессом 3165 Couldn’t open .inf file Не удается открыть INF-файл 3166 Cannot locate the requested Xbase memo file Не удается найти затребованный файл Memo Xbase 3167 Record is deleted Запись удалена 3168 Invalid .inf file Недопустимый INF-файл 3169 The Microsoft Jet database engine could not execute the SQL statement because it contains a field that has an invalid data type Инструкция SQL не может быть выполнена ядром базы данных Microsoft Jet, так как содержит поле с недопустимым типом данных 3170 Couldn’t find installable ISAM Невозможно найти устанавливаемый драйвер ISAM 3171 Couldn’t find network path or user name Невозможно найти сетевой путь или имя пользователя 3172 Couldn’t open Paradox.net Невозможно открыть файл Paradox.net 3173 Couldn’t open table ‘MsysAccounts’ in Не удается открыть таблицу MsysAccounts 3174 Couldn’t open table ‘MSysGroups’ in the workgroup information file Не удается открыть таблицу MSysGroups в файле системной базы данных 3175 Date is out of range or is in an invalid format Дата выходит за пределы допустимого диапазона или имеет ошибочный формат 3176 Couldn’t open file <name> Не удается открыть файл <name> 3177 Not a valid table name Недопустимое имя таблицы 3179 Encountered unexpected end of file Обнаружен ошибочный конец файла 3180 Couldn’t write to file <name> Невозможна запись в файл <name> 3181 Invalid range Недопустимый диапазон 3182 Invalid file format Недопустимый формат файла 3183 Not enough space on temporary disk Недостаточно места на временном диске 3184 «Couldn’t execute query; couldn’t find linked table» «Выполнение запроса невозможно; не удается найти присоединенную (связанную) таблицу» 3185 SELECT INTO on a remote database tried to produce too many fields Инструкция SELECT INTO для удаленной базы данных осуществляет попытку создать слишком много полей 3186 «Couldn’t save; currently locked by user<name> on machine <name>» «Сохранение невозможно; блокировка пользователем <name> на машине <name>» 3187 «Couldn’t read; currently locked by user<name> on machine <name>» «Чтение невозможно; блокировка пользователем <name> на машине<name>» 3188 «Couldn’t update; currently locked by another session on this machine» «Обновление невозможно; блокировка другим сеансом данной машины» 3189 Table <name> is exclusively locked by user <name> on machine <name> Таблица <name> открыта с монопольным доступом пользователем<name> на машине <name> 3190 Too many fields defined Определено слишком много полей 3191 Can’t define field more than once Нельзя определить поле более одного раза 3192 Couldn’t find output table <name> Не удается найти выходную таблицу<name> 3196 The database <database name> is already in use by another person or proccess. When the database is available, try the operation again База данных <name> уже используется другим пользователем или процессом. Повторите операцию, когда база данных снова станет доступной 3197 The Microsoft Jet database engine stopped the process because you and another user are attempting to change the same data at the same time Процесс остановлен ядром базы данных Microsoft Jet, так как другой пользователь пытается одновременно изменить те же данные 3198 Couldn’t start session. Too many sessions already active Невозможно начать сеанс. Уже запущено слишком много сеансов 3199 Couldn’t find reference Не удается найти ссылку 3200 The record cannot be deleted or changed because table <name> includes related records Удаление или изменение записи невозможно. В таблице <name> имеются связанные записи 3201 You can’t add or change a record because a related record is required in table <name> Невозможно добавление или изменение записи. Для обеспечения целостности данных необходимо наличие связанной записи в таблице <name> 3202 «Couldn’t save; currently locked by another user» «Сохранение невозможно; блокировка другим пользователем» 3203 Subqueries cannot be used in the expression <expression> В выражении <expression> нельзя указывать подчиненный запрос 3204 Database already exists База данных уже существует 3205 Too many crosstab column headers<value> Слишком много заголовков столбцов <value> для перекрестной таблицы 3206 Can’t create a relationship between a field and itself Невозможно создать связь поля с этим же полем 3207 Operation not supported on a Paradox table with no primary key Операция не поддерживается для таблиц Paradox без ключевых полей 3208 Invalid Deleted setting in the Xbase key of the Windows Registry Недопустимое значение параметра Deleted в записи Xbase реестра Windows 3210 The connection string is too long Слишком длинная строка подключения 3211 The database engine couldn’t lock table<name> because it’s already in use by another person or process Таблица <name> не может быть заблокирована ядром базы данных. Она уже используется другим пользователем или процессом 3212 «Couldn’t lock table <name>; currently in use by user <name> on machine<name>» «Не удается блокировать таблицу<name>; она используется пользователем <name> на машине <name>» 3213 Invalid Date setting in the Xbase key of the Windows Registry Недопустимое значение параметра ‘Date’ в записи Xbase реестра Windows 3214 Invalid Mark setting in the Xbase key of the Windows Registry Недопустимое значение параметра ‘Mark’ в записи Xbase реестра Windows 3215 Too many Btrieve tasks Слишком много задач Btrieve 3216 Parameter <name> specified where a table name is required Параметр <name> задан вместо имени таблицы 3217 Parameter <name> specified where a database name is required Параметр <name> задан вместо имени базы данных 3218 «Couldn’t update; currently locked» «Обновление невозможно; установлена блокировка» 3219 Invalid operation Недопустимая операция 3220 Incorrect collating sequence Ошибочная таблица сортировки 3221 Invalid settings in the Btrieve key of the Windows Registry Недопустимые значения параметров в записи Btrieve реестра Windows 3222 Query can’t contain a Database parameter Запрос не может иметь параметр ‘База данных’ (Database) 3223 <Parameter name> is invalid because it’s longer than 64 characters or contains invalid characters Недопустимое имя параметра < Parameter name>, имеющее слишком большую длину или содержащее недопустимые символы 3224 Can’t read Btrieve data dictionary Невозможно прочитать словарь данных Btrieve 3225 Encountered a record locking deadlock while performing a Btrieve operation Данная блокировка записи накладывает условие взаимоблокировки при выполнении операции Btrieve 3226 Errors encountered while using the Btrieve DLL Ошибки при использовании библиотеки Btrieve 3227 Invalid Century setting in the Xbase key of the Windows Registry Недопустимое значение параметра Century в записи Xbase реестра Windows 3228 Invalid CollatingScqucnce setting in the Paradox key of the Windows Registry Недопустимое значение параметра CollatingScquence в записи Paradox реестра Windows 3229 Btrieve — can’t change field Btrieve — изменение значения поля невозможно 3230 Out-of-date Paradox lock file Устаревший файл блокировок Paradox 3231 «ODBC — field would be too long; data truncated» «ODBC — слишком большое поле; произошло усечение данных» 3232 ODBC — couldn’t create table ODBC — создание таблицы невозможно 3234 ODBC — remote query timeout expired ODBC — время ожидания для выполнения удаленного запроса истекло 3235 ODBC — data type not supported on server ODBC — тип данных не поддерживается сервером 3238 ODBC — data out of range ODBC — данные выходят за пределы допустимого диапазона 3239 Too many active users Слишком много пользователей 3240 Btrieve — missing Btrieve engine Btrieve — отсутствует ядро Btrieve 3241 Btrieve — out of resources Btrieve — недостаток ресурсов 3242 Invalid reference in SELECT statement Недопустимая ссылка в инструкции SELECT 3243 None of the import field names match fields in the appended table Ни одно из имен импортируемых полей не совпадает с именами полей таблицы-получателя 3244 Can’t import password-protected spreadsheet Невозможен импорт электронной таблицы, защищенной паролем 3245 Couldn’t parse field names from the first row of the import table Невозможно выделить имена полей из первой строки, импортируемой таблицы 3246 Operation not supported in transactions Операция не поддерживается в транзакциях 3247 ODBC — linked table definition has changed ODBC — было изменено описание связанной таблицы 3248 Invalid NetworkAccess setting in the Windows Registry Недопустимое значение параметра NetworkAccess в записи реестра Windows 3249 Invalid PageTimeout setting in the Windows Registry Недопустимое значение параметра PageTimeout в записи реестра Windows 3250 Couldn’t build key Невозможно построение ключа 3251 Operation is not supported for this type of object Операция не поддерживается для объектов этого типа 3252 Can’t open a form whose underlying query contains a user-defined function that attempts to set or get the form’s RecordsetClone property Невозможно открыть форму: базовый запрос содержит определяемую пользователем функцию, задающую или получающую значение свойства RecordsetClone 3254 ODBC — can’t lock all records ODBC — блокировка всех записей невозможна 3256 Index file not found Не найден индексный файл 3257 Syntax error in WITH OWNER- ACCESS OPTION declaration Ошибка синтаксиса в описании WITH OWNERACCESS OPTION 3258 The SQL statement couldn’t be executed because it contains ambiguous outer joins. To force one of the joins to be performed first, create a separate query that performs the first join and then include that query in your SQL statement Невозможно выполнить инструкцию SQL, так как запрос содержит неоднозначные внешние связи. Для указания связи, выполняемой первой, создайте отдельный запрос и включите его в инструкцию SQL 3259 Invalid field data type Недопустимый тип данных поля 3260 «Couldn’t update; currently locked by user <name> on machine <name>» «Обновление невозможно; блокировка установлена пользователем<name> на машине <name>» 3261 Table <name> is exclusively locked by user <name> on machine <name> Таблица <name> блокирована с монопольным доступом пользователем<name> на машине <name> 3262 «Couldn’t lock table <name>; currently in use by user <name> on machine<name>» «Блокировка таблицы <name> невозможна; используется пользователем<name> на машине <name>» 3263 Invalid Database object Недопустимый объект Database 3264 No field defined — cannot append TableDef or Index Поля не определены — невозможно добавление объектов TableDef или Index 3265 Item not found in this collection Элемент не обнаружен в данном семействе 3266 Can’t append a Field that is already a part of a Fields collection Добавление невозможно. Поле является частью семейства Fields 3267 Property can be set only when the Field is part of a Recordset object’s Fields collection Свойство может быть определено, только если это поле является частью семейства Fields объекта Recordset 3268 Can’t set this property once the object is part of a collection Невозможно задание данного свойства, если объект является частью семейства 3269 Can’t append an Index that is already a part of an Indexes collection Добавление невозможно. Индекс является частью семейства Indexes 3270 Property not found Свойство не найдено 3271 Invalid property value Недопустимое значение свойства 3272 Object isn’t a collection Объект не является семейством 3273 Method not applicable for this object Метод неприменим к данному объекту 3274 External table isn’t in the expected format Внешняя таблица не имеет предполагаемый формат 3275 Unexpected error from external database driver <error number> Непредвиденная ошибка драйвера внешней базы данных <error number> 3276 Invalid database object reference Недопустимая ссылка на объект Database 3277 Can’t have more than 10 fields in an index Индекс не может содержать более десяти полей 3278 The Microsoft Jet database engine has not been initialized Не выполнена инициализация ядра базы данных Microsoft Jet 3279 The Microsoft Jet database engine has already been initialized Инициализация ядра базы данных Microsoft Jet уже выполнена 3280 Can’t delete a field that is part of an index or is needed by the system Невозможно удаление поля, являющегося частью индекса или необходимого системе 3281 Can’t delete this index or table. It is either the current index or is used in a relationship Удаление индекса или таблицы невозможно. Объект является текущим индексом или используется для 3282 Operation not supported on a table that contains data Операция не поддерживается для таблицы, содержащей данные 3283 Primary key already exists Ключ уже существует 3284 Index already exists Индекс уже существует 3285 Invalid index definition Недопустимое определение индекса 3286 Format of memo file doesn’t match specified external database format Формат файла Memo не соответствует указанному формату внешней базы данных 3287 Can’t create index on the given field Невозможно создание индекса для данного поля 3288 Paradox index is not primary Индекс Paradox не является первичным 3289 Syntax error in CONSTRAINT clause Ошибка синтаксиса в предложении CONSTRAINT 3290 Syntax error in CREATE TABLE statement Ошибка синтаксиса в инструкции CREATE TABLE 3291 Syntax error in CREATE INDEX statement Ошибка синтаксиса в инструкции CREATE INDEX 3292 Syntax error in field definition Ошибка синтаксиса при определении поля 3293 Syntax error in ALTER TABLE statement Ошибка синтаксиса в инструкции ALTER TABLE 3294 Syntax error in DROP INDEX statement Ошибка синтаксиса в инструкции DROP INDEX 3295 Syntax error in DROP TABLE or DROP INDEX Ошибка синтаксиса в инструкции DROP TABLE или DROP INDEX 3296 Join expression not supported Не поддерживается выражение объединения 3297 Couldn’t import table or query. No records found, or all records contain errors Невозможен импорт таблицы или запроса. Записи не обнаружены, или все записи содержат ошибки 3298 There are several tables with that name. Please specify owner in the format’owner.table’ Существует несколько таблиц с данным именем. Укажите владельца в формате ‘owner.table’ 3299 ODBC Specification Conformance Error <message>. Report this error to the developer of your application Ошибка согласования спецификации ODBC <message>. Сообщите о данной ошибке разработчику используемого приложения 3300 Can’t create a relationship Не удается установить связь 3301 «Can’t perform this operation; features in this version are not available in databases with older formats» «Выполнение операции невозможно; возможности данной версии недоступны в базах данных старого формата» 3303 Can’t delete this field. It’s part of one or more relationships Удаление данного поля невозможно. Оно участвует в одной или нескольких связях 3304 You must enter a personal identifier(PID) consisting of at least 4 and no more than 20 characters and digits Необходимо ввести код учетной записи, содержащий от 4 до 20 символов и цифр 3305 Invalid connection string in pass-through query Недопустимая строка подключения в запросе к серверу 3306 You’ve written a subquery that can return more than one field without using the EXISTS reserved word in the main query’s FROM clause. Revise the SELECT statement of the subquery to request only one field Из подчиненного запроса, который не использует ключевое слово EXISTS, возвращается не более одного поля. Укажите в инструкции SELECT подчиненного запроса возвращение только одного поля 3307 The number of columns in the two selected tables or queries of a union query don’t match В таблицах или запросах, выбранных в запросе на объединение, не совпадает число столбцов 3308 Invalid TOP argument in select query Недопустимый аргумент ТОР запроса на выборку 3309 Property setting can’t be larger than 2K Размер значения свойства не должен превышать 2 Кбайт 3310 This property isn’t supported for external data sources or for databases created with a previous version of Microsoft Jet Данное свойство не поддерживается для внешних источников данных или для баз данных, созданных в предыдущей версии ядра Microsoft Jet 3311 Property specified already exists Указанное свойство уже определено 3312 Validation rules and default values can’t be placed on system or linked tables Нельзя задавать условия на значения или значения по умолчанию для системных или присоединенных (связанных) таблиц 3313 Can’t place this validation expression on this field Невозможно задать выражение условия на значения для этого поля 3314 The field <name> can’t contain a Null value because the Required property for this field is set to True. Enter a value in this field Поле <name> не может содержать значение Null, так как свойство Required имеет значение True. Введите значение в поле 3315 Field <name> can’t be a zero-length string Поле <name> не допускает ввод пустых строк 3316 <Tablelevel validation text> Текст условия на значение уровня таблицы 3317 One or more values are prohibited by the validation rule <rule> set for <name>. Enter a value that the expression for this field can accept Одно или несколько из введенных значений нарушают условие на значение <rule>, заданное для <name>. Введите значение, допускаемое выражением для данного поля 3318 Values specified in a TOP clause are not allowed in delete queries or reports Значения, указанные в предложении ТОР, не допускаются в запросах на удаление записей или в отчетах 3319 Syntax error in union query Ошибка синтаксиса в запросе на объединение 3320 <Error> in table-level validation expression <Еггог> в выражении условия на значение уровня таблицы 3321 No database specified in connection string or IN clause He задана база данных в строке подключения или в предложении IN 3322 Crosstab query contains one or more invalid fixed column headings Перекрестный запрос содержит один или несколько недопустимых заголовков столбцов 3323 The query cannot be used as a row source Не допускается использование этого запроса в качестве источника строк 3324 The query is a DDL query and cannot be used as a row source Данный запрос является управляющим запросом и его нельзя использовать в качестве источника строк 3325 Pass-through query with Returns- Records property set to True did not return any records Запрос к серверу, свойство ReturnsRecords которого имеет значение True, не вернул ни одной записи 3326 This Recordset is not updatable Объект Recordset не является обновляемым 3334 Can be present only in version 1.0 format Возможно представление только в формате версии 1.0 3336 Btrieve: Invalid IndexDDF option in initialization setting Btrieve: недопустимое значение параметра инициализации IndexDDF 3337 Invalid DataCodePage option in initialization setting Недопустимое значение параметра инициализации DataCodePage 3338 Btrieve: Xtrieve options aren’t correct in initialization setting Btrieve: не исправлены параметры инициализации Xtrieve 3339 Btrieve: Invalid IndexDeleteRenumber option in initialization setting Btrieve: недопустимое значение параметра инициализации IndexDeleteRenumber 3340 Query <name> is corrupt Запрос <name> поврежден 3341 The current field must match the join key <name> in the table that serves as the ‘one’ side of one-to-many relationship. Enter a record in the ‘one’ side table with the desired key value, and then make the entry with the desired join key in the ‘many’ side Текущее поле после обновления должно содержать подходящий ключ связи <name> со стороны ‘один’ внешнего объединения. Введите на стороне ‘один’ запись с требуемым значением ключа связи, а затем создайте запись с тем же значением ключа в таблице на стороне ‘многие’ 3342 Invalid Memo or OLE Object in sub- query <name> Ошибочное поле Memo или поле объекта ActiveX в подчиненном запросе <name> 3343 Unrecognized database format<filename> Нераспознаваемый формат базы данных <filename> 3344 The database engine does not recognize either the field <name> in a validation expression, or the default value in the table <name> Имя поля <name> в выражении для условия на значение или в значении по умолчанию в таблице <name> не распознается ядром базы данных 3345 Unknown or invalid field reference<name> Недопустимая или неизвестная ссылка на поле <name> 3346 Number of query values and destination fields aren’t the same Не совпадает число значении запроса и число результирующих полей 3349 Numeric field overflow Переполнение числового поля 3350 Object is invalid for operation Недопустимый объект для данной операции 3351 The ORDER BY expression <expression> includes fields that aren’t selected by the query. Only those fields requested in the first query can be in- cluded in an ORDER BY expression В выражение ORDER BY <expression> включены поля, не выбранные в запросе. Выражение ORDER BY может содержать только поля, затребованные в первом запросе 3352 No destination field name in INSERT INTO statement <statement> В инструкции INSERT INTO <statement> отсутствует имя результирующего поля 3353 Btrieve: Can’t find file RELD.DDF Btrieve: He удается найти файл FIELD.DDF 3354 At most one record can be returned by this subquery Данный подчиненный запрос должен возвращать не более одной записи 3355 Syntax error in default value Ошибка синтаксиса в значении по умолчанию 3356 You attempted to open a database that is already opened exclusively by user<name> on machine <name>. Try again when the database is available Попытка открыть базу данных, открытую пользователем <name> на машине <name> для монопольного доступа. Повторите попытку, когда база данных освободится 3357 This query is not a properly formed data-definition query Данный запрос не является правильно заданным управляющим запросом 3358 Can’t open the Microsoft Jet engine workgroup information file Не удается открыть системную базу данных ядра Microsoft Jet 3359 Pass-through query must contain at least one character Запрос к серверу должен содержать, по крайней мере, один символ 3360 Query is too complex Слишком сложный запрос 3361 Unions not allowed in a subquery В подчиненном запросе не допускаются объединения 3362 Single-row update/delete affected more than one row of a linked table. Unique index contains duplicate values Обновление/удаление строки влияет на несколько строк присоединенной таблицы. Повтор значений в уникальном индексе 3364 Can’t use Memo or OLE Object field<name> in the SELECT clause of a union query В предложении SELECT запроса на объединение не допускается использование поля Memo или поля объекта ActiveX <name> 3365 Can’t set this property for remote objects Невозможно установить значение данного свойства для внешних объектов 3366 Can’t append a relation with no fields defined Невозможно добавить связь, не определив поля 3367 Can’t append. An object with that name already exists in the collection Добавление объекта невозможно. Он уже входит в семейство 3368 Relationship must be on the same number of fields with the same data types Отношение должно быть задано для одинакового количества полей с одинаковыми типами данных 3370 Can’t modify the design of table<name> It’s in a read-only database Невозможно изменение структуры таблицы «name». База данных доступна только для чтения 3371 Can’t find table or constraint Не удается найти таблицу или индекс 3372 No such index <name> on table<name> Индекс <name> не существует в таблице <name> 3373 Can’t create relationship. Referenced Не удается создать связь. Указанная 3374 The specified fields are not uniquely indexed in table <name> Указанные поля не имеют уникального индекса в таблице <name> 3375 Table <name> already has an index named <name> Таблица <name> уже имеет индекс с именем <name> 3376 Table <name> doesn’t exist Таблица <name> не существует 3377 No such relationship <name> on table<name> Отношение <name> для таблицы<name> не существует 3378 There is already a relationship named<name> in the current database Связь <name> уже существует в текущей базе данных 3379 Can’t create relationships to enforce referential integrity. Existing data in table <name> violates referential integrity rules in table <name> Невозможно обеспечить целостность данных. Данные таблицы<name> нарушают условия для связи с таблицей <name> 3380 Field <name> already exists in table<name> Поле <name> уже существует в таблице <name> 3381 There is no field named <name> in table <name> Поле <name> отсутствует в таблице<name> 3382 Size of field <name> is too long Слишком длинное поле <name> 3383 Can’t delete field <name> It’s part of one or more relationships Невозможно удалить поле <name>. Оно является частью одной или нескольких связей 3384 Can’t delete a built-in property Невозможно удаление встроенного свойства 3385 User-defined properties don’t support a Null value Свойства, определяемые пользователем, не допускают задание пустых значении (Null) 3386 Property <name> must be set before using this method Перед использованием данного метода необходимо задать значение свойства <name> 3388 Unknown function <name> in validation expression or default value on<name> Неизвестная функция <name> в выражении условия на значение или в значении по умолчанию для <name> 3389 Query support unavailable Поддержка запроса недоступна 3390 Account name already exists Имя учетной записи уже существует 3393 Can’t perform join, group, sort, or indexed restriction. A value being searched or sorted on is too long Невозможно выполнить объединение, группировку, сортировку или отбор по индексу. Слишком длинное значение, используемое для поиска или сортировки 3394 «Can’t save property; property is a schema property» «Сохранение свойства невозможно; свойство схемы» 3396 Can’t perform cascading operation. Since related records exist in table<name>, referential integrity rules would be violated Невозможно выполнить каскадную операцию, поскольку наличие в таблице <name> связанных записей приведет к нарушению целостности данных 3397 Can’t perform cascading operation. There must be a related record in table<name> Невозможно выполнение каскадной операции. Необходимо наличие связанных записей в таблице <name> 3398 Can’t perform cascading operation. It would result in a null key in table<name> Невозможно выполнить каскадную операцию, которая приведет к появлению пустого ключевого поля в таблице <name> 3399 Can’t perform cascading operation. It would result in a duplicate key in table<name> Невозможно выполнить каскадную операцию, которая приведет к появлению повторяющихся значений в ключевом поле таблицы <name> 3400 Can’t perform cascading operation. It would result in two updates to field <name> in table <name> Невозможно выполнить каскадную операцию, которая приведет к повторному обновлению поля <name> в таблице <name> 3401 Can’t perform cascading operation. It would cause field <name> to become Null, which is not allowed Невозможно выполнить каскадную операцию, которая приведет к появлению недопустимого пустого (Null) значения в поле <name> 3402 Can’t perform cascading operation. It would cause field <name> to become a zero-length string, which is not allowed Невозможно выполнить каскадную операцию, которая приведет к появлению недопустимой пустой строки в поле <name>

“Abort, Retry, Fail?” – MS-DOS error message circa 1986

This post provides a complete guide to VBA Error Handing. If you are looking for a quick summary then check out the quick guide table in the first section.

If you are looking for a particular topic on VBA Error Handing then check out the table of contents below(if it’s not visible click on the post header).

If you are new to VBA Error Handling, then you can read the post from start to finish as it is laid out in logical order.

Contents

  • 1 A Quick Guide to Error Handing
  • 2 The Webinar
  • 3 Download the Error Handling Library
  • 4 Introduction
  • 5 VBA Errors
    • 5.1 Syntax Errors
    • 5.2 Compilation Errors
      • 5.2.1 Using Debug->Compile
      • 5.2.2 Debug->Compile Error Summary
      • 5.2.3 Debug->Compile Usage
    • 5.3 Runtime Errors
      • 5.3.1 Expected Versus Unexpected Errors
    • 5.4 Runtime Errors that are not VBA Errors
  • 6 The On Error Statement
    • 6.1 On Error GoTo 0
    • 6.2 On Error Resume Next
    • 6.3 On Error GoTo [label]
    • 6.4 On Error GoTo -1
    • 6.5 Using On Error
  • 7 Resume Next
  • 8 The Err Object
    • 8.1 Getting the Line Number
    • 8.2 Using Err.Raise
    • 8.3 Using Err.Clear
  • 9 Logging
  • 10 Other Error Related Items
    • 10.1 Error Function
    • 10.2 Error Statement
  • 11 A Simple Error Handling Strategy
    • 11.1 The Basic Implementation
  • 12 A Complete Error Handling Strategy
    • 12.1 An Example of using this strategy
  • 13 Error Handling in a Nutshell
  • 14 What’s Next?

A Quick Guide to Error Handing

Item Description
On Error Goto 0 When error occurs, the code stops and displays the error.
On Error Goto -1 Clears the current error setting and reverts to the default.
On Error Resume Next Ignores the error and continues on.
On Error Goto [Label] Goes to a specific label when an error occurs.
This allows us to handle the error.
Err Object When an error occurs the error information is stored here.
Err.Number The number of the error.
(Only useful if you need to check a specific error occurred.)
Err.Description Contains the error text.
Err.Source You can populate this when you use Err.Raise.
Err.Raise A function that allows you to generate your own error.
Error Function Returns the error text from an error number.
Obsolete.
Error Statement Simulates an error. Use Err.Raise instead.

The Webinar

Members of the Webinar Archives can access the webinar for this article by clicking on the image below.

(Note: Archive members have access to the webinar archive.)

vba error handling video

Download the Error Handling Library

Introduction

Error Handling refers to code that is written to handle errors which occur when your application is running. These errors are normally caused by something outside your control like a missing file, database being unavailable, data being invalid etc.

If we think an error is likely to occur at some point, it is good practice to write specific code to handle the error if it occurs and deal with it.

For all other errors, we use generic code to deal with them. This is where the VBA error handling statement comes into play. They allow our application to deal gracefully with any errors we weren’t expecting.

To understand error handling we must first understand the different types of errors in VBA.

VBA Error Handling

VBA Errors

There are three types of errors in VBA:

  1. Syntax
  2. Compilation
  3. Runtime

We use error handling to deal with runtime errors. Let’s have a look at each of these error types so that it is clear what a runtime error is.

Syntax Errors

If you have used VBA for any length of time you will have seen a syntax error. When you type a line and press return, VBA will evaluate the syntax and if it is not correct it will display an error message.

For example if you type If and forget the Then keyword, VBA will display the following error message

VBA Error Handling

Some examples of syntax errors are

' then is missing
If a > b

' equals is missing after i
For i 2 To 7

' missing right parenthesis
b = left("ABCD",1

Syntax errors relate to one line only. They occur when the syntax of one line is incorrect.

Note: You can turn off the Syntax error dialog by going to Tools->Options and checking off “Auto Syntax Check”. The line will still appear red if there is an error but the dialog will not appear.

Compilation Errors

Compilation errors occur over more than one line. The syntax is correct on a single line but is incorrect when all the project code is taken into account.

Examples of compilation errors are:

  • If statement without corresponding End If statement
  • For without Next
  • Select without End Select
  • Calling a Sub or Function that does not exist
  • Calling a Sub or Function with the wrong parameters
  • Giving a Sub or Function the same name as a module
  • Variables not declared(Option Explicit must be present at the top of the module)

The following screenshot shows a compilation error that occurs when a For loop has no matching Next statement.

VBA Error Handling

Using Debug->Compile

To find compilation errors, we use Debug->Compile VBA Project from the Visual Basic menu.

When you select Debug->Compile, VBA displays the first error it comes across.

When this error is fixed, you can run Compile again and VBA will then find the next error.

Debug->Compile will also include syntax errors in it’s search which is very useful.

If there are no errors left and you run Debug->Compile , it may appear that nothing happened. However, “Compile” will be grayed out in the Debug menu. This means your application has no compilation errors at the current time.

Debug->Compile Error Summary

  • Debug->Compile finds compilation(project wide) errors.
  • It will also find syntax errors.
  • It finds one error each time you use it.
  • When there are no compilation errors left the Compile option will appear grayed out in the menu.

Debug->Compile Usage

You should always use Debug->Compile before you run your code. This ensures that your code has no compilation errors when you run it.

If you do not run Debug->Compile then VBA may find compile errors when it runs. These should not be confused with Runtime errors.

Runtime Errors

Runtime errors occur when your application is running. They are normally outside of your control but can be caused by errors in your code.

VBA Error Handling

For example, imagine your application reads from an external workbook. If this file gets deleted then VBA will display an error when your code tries to open it.

Other examples of runtime errors are

  • a database not being available
  • the user entering invalid data
  • a cell containing text instead of a number

As we have seen, the purpose of error handling is to deal with runtime errors when they occur.

Expected Versus Unexpected Errors

When we think a runtime error could occur we put code in place to handle it. For example, we would normally put code in place to deal with a file not being found.

The following code checks if the file exists before it tries to open it. If the file does not exist then a user friendly message is displayed and the code exits the sub.

' https://excelmacromastery.com/
Sub OpenFile()
    
    Dim sFile As String
    sFile = "C:docsdata.xlsx"
    
    ' Use Dir to check if file exists
    If Dir(sFile) = "" Then
        ' if file does not exist display message
        MsgBox "Could not find the file " & sFile
        Exit Sub
    End If
    
    ' Code will only reach here if file exists
    Workbooks.Open sFile
    
End Sub

When we think an error is likely to occur at some point, it is good practice to add code to handle the situation. We normally refer to these errors as expected errors.

If we don’t have specific code to handle an error it is considered an unexpected error. We use the VBA error handling statements to handle the unexpected errors.

Runtime Errors that are not VBA Errors

Before we look at the VBA Handling there is one type of error we must mention. Some runtime errors are not considered errors by VBA but only by the user.

Let me explain this with an example. Imagine you have an application that requires you to add the values in the variables a and b

result = a + b

Let’s say you mistakenly use an asterisk instead of the plus sign

result = a * b

This is not a VBA error. Your code syntax is perfectly legal. However, from your requirements point of view it is an error.

These errors cannot be dealt with using error handling as they obviously won’t generate any error. You can deal with these errors using Unit Testing and Assertions. I have an in-depth post about using VBA assertions – see How to Make Your Code BulletProof.

The On Error Statement

As we have seen there are two ways to treat runtime errors

  1. Expected errors – write specific code to handle them.
  2. Unexpected errors – use VBA error handling statements to handle them.

The VBA On Error statement is used for error handling. This statement performs some action when an error occurs during runtime.

There are four different ways to use this statement

  1. On Error GoTo 0 – the code stops at the line with the error and displays a message.
  2. On Error Resume Next – the code moves to next line. No error message is displayed.
  3. On Error GoTo [label] – the code moves to a specific line or label. No error message is displayed. This is the one we use for error handling.
  4. On Error GoTo -1 – clears the current error.

Let’s look at each of these statements in turn.

On Error GoTo 0

This is the default behavior of VBA. In other words, if you don’t use On Error then this is the behavior you will see.

When an error occurs, VBA stops on the line with the error and displays the error message. The application requires user intervention with the code before it can continue. This could be fixing the error or restarting the application. In this scenario no error handling takes place.

Let’s look at an example. In the following code, we have not used any On Error line so VBA will use the On Error GoTo 0 behavior by default.

' https://excelmacromastery.com/
Sub UsingDefault()

    Dim x As Long, y As Long
    
    x = 6
    y = 6 / 0
    x = 7

End Sub

The second assignment line results in a divide by zero error. When we run this code we will get the error message shown in the screenshot below

VBA Error Handling

When the error appears you can choose End or Debug

If you select End then the application simply stops.
If you select Debug the application stops on the error line as the screenshot below shows

VBA Error Handling

This behaviour is fine when you are writing VBA code as it shows you the exact line with the error.

This behavior is unsuitable for an application that you are given to a user. These errors look unprofessional and they make the application look unstable.

An error like this is essentially the application crashing. The user cannot continue on without restarting the application. They may not use it at all until you fix the error for them.

By using On Error GoTo [label] we can give the user a more controlled error message. It also prevents the application stopping. We can get the application to perform in a predefined manner.

On Error Resume Next

Using On Error Resume Next tells VBA to ignore the error and continue on.

There are specific occasions when this is useful. Most of the time you should avoid using it.

If we add Resume Next to our example Sub then VBA will ignore the divide by zero error

' https://excelmacromastery.com/
Sub UsingResumeNext()

    On Error Resume Next
    
    Dim x As Long, y As Long
    
    x = 6
    y = 6 / 0
    x = 7

End Sub

It is not a good idea to do this. If you ignore the error, then the behavior can be unpredictable. The error can affect the application in multiple ways.You could end up with invalid data. The problem is that you aren’t aware that something went wrong because you have suppressed the error.

The code below is an example of where using Resume Next is valid

' https://excelmacromastery.com/
Sub SendMail()

   On Error Resume Next
   
    ' Requires Reference:
    ' Microsoft Outlook 15.0 Object Library
    Dim Outlook As Outlook.Application
    Set Outlook = New Outlook.Application

    If Outlook Is Nothing Then
        MsgBox "Cannot create Microsoft Outlook session." _
                   & " The email will not be sent."
        Exit Sub
    End If
    
End Sub

In this code we are checking to see if Microsoft Outlook is available on a computer. All we want to know is if it is available or not. We are not interested in the specific error.

In the code above, we continue on if there is an error. Then in the next line we check the value of the Outlook variable. If there has been an error then the value of this variable will be set to Nothing.

This is an example of when Resume could be useful. The point is that even though we use Resume we are still checking for the error. The vast majority of the time you will not need to use Resume.

On Error GoTo [label]

This is how we use Error Handling in VBA. It is the equivalent of the Try and Catch functionality you see in languages such as C# and Java.

When an error occurs you send the error to a specific label. It is normally at the bottom of the sub.

Let’s apply this to the sub we have been using

' https://excelmacromastery.com/
Sub UsingGotoLine()

    On Error GoTo eh
    
    Dim x As Long, y As Long
    
    x = 6
    y = 6 / 0
    x = 7
    
Done:
    Exit Sub
eh:
    MsgBox "The following error occurred: " & Err.Description
End Sub

The screenshot below shows what happens when an error occurs

VBA Error Handling

VBA jumps to the eh label because we specified this in the On Error Goto line.

Note 1: The label we use in the On…GoTo statement, must be in the current Sub/Function. If not you will get a compilation error.

Note 2: When an error occurs when using On Error GoTo [label], the error handling returns to the default behaviour i.e. The code will stop on the line with the error and display the error message. See the next section for more information about this.

On Error GoTo -1

This statement is different than the other three. It is used to clear the current error rather than setting a particular behaviour.

When an error occurs using On Error GoTo [label], the error handling behaviour returns to the default behaviour i.e. “On Error GoTo 0”. That means that if another error occurs the code will stop on the current line.

This behaviour only applies to the current sub. Once we exit the sub, the error will be cleared automatically.

Take a look at the code below. The first error will cause the code to jump to the eh label. The second error will stop on the line with the 1034 error.

' https://excelmacromastery.com/
Sub TwoErrors()

    On Error Goto eh
        
    ' generate "Type mismatch" error
    Error (13)

Done:
    Exit Sub
eh:
    ' generate "Application-defined" error
    Error (1034)
End Sub

If we add further error handling it will not work as the error trap has not been cleared.

In the code below we have added the line

On Error Goto eh_other

after we catch the first error.

This has no effect as the error has not been cleared. In other words the code will stop on the line with the error and display the message.

' https://excelmacromastery.com/
Sub TwoErrors()

    On Error Goto eh
        
    ' generate "Type mismatch" error
    Error (13)

Done:
    Exit Sub
eh:
    On Error Goto eh_other
    ' generate "Application-defined" error
    Error (1034)
Exit Sub
eh_other:
    Debug.Print "eh_other " & Err.Description
End Sub

To clear the error we use On Error GoTo -1. Think of it like setting a mouse trap. When the trap goes off you need to set it again.

In the code below we add this line and the second error will now cause the code to jump to the eh_other label

' https://excelmacromastery.com/
Sub TwoErrors()

    On Error Goto eh
        
    ' generate "Type mismatch" error
    Error (13)

Done:
    Exit Sub
eh:
    ' clear error
    On Error Goto -1
    
    On Error Goto eh_other
    ' generate "Application-defined" error
    Error (1034)
Exit Sub
eh_other:
    Debug.Print "eh_other " & Err.Description
End Sub

Note 1: There are probably rare cases where using On Error GoTo -1 is useful. In most cases using Resume Next is better as it clears the error and resumes the code at the next line after the error occurs.

Note 2: The Err Object has a member Clear. Using Clear clears the text and numbers in the Err object, but it does NOT reset the error.

Using On Error

As we have seen, VBA will do one of three things when an error occurs

  • Stop and display the error.
  • Ignore the error and continue on.
  • Jump to a specific line.

VBA will always be set to one of these behaviors. When you use On Error, VBA will change to the behaviour you specify and forget about any previous behavior.

In the following Sub, VBA changes the error behaviour each time we use the On Error statement

' https://excelmacromastery.com/
Sub ErrorStates()

    Dim x As Long
    
    ' Go to eh label if error
    On Error Goto eh
    
    ' this will ignore the error on the following line
    On Error Resume Next
    x = 1 / 0
    
    ' this will display an error message on the following line
    On Error Goto 0
    x = 1 / 0
  
Done:  
   Exit Sub
eh:
    Debug.Print Err.Description
End Sub

Resume Next

The Resume Next statement is used to clear the error and then resume the code from the line after where the error occurred.

If your code can have multiple errors and you want to keep detecting them then this line is very useful.

For example, in the following code we want to resume the code after the error has been reported:

Private Sub Main()

    On Error Goto eh
    
    Dim i As Long
    For i = 1 To 3
        ' Generate type mismatch error
         Error 13
    Next i

done:
    Exit Sub
eh:
    Debug.Print i, Err.Description
End Sub

 
We could use On Error Goto -1 to clear the code and then use a goto statement to go back to the code like this:

Private Sub Main()

    On Error Goto eh
    
    Dim i As Long
    For i = 1 To 3
        ' Generate type mismatch error
         Error 13
continue:
    Next i

done:
    Exit Sub
eh:
    Debug.Print i, Err.Description
    On Error Goto -1 ' clear the error
    Goto continue ' return to the code
End Sub

 
The Resume Next provides a nicer way of doing it and it always means the code is much clearer and easier to understand:

Private Sub Main()

    On Error Goto eh
    
    Dim i As Long
    For i = 1 To 3
        ' Generate type mismatch error
         Error 13
continue:
    Next i

done:
    Exit Sub
eh:
    Debug.Print i, Err.Description
    ' clear the error and return to the code
    Resume Next  
End Sub

The Err Object

When an error occurs you can view details of the error using the Err object.

When an runtime error occurs, VBA automatically fills the Err object with details.

The code below will print “Error Number: 13 Type Mismatch” which occurs when we try to place a string value in the long integer total

' https://excelmacromastery.com/
Sub UsingErr()

    On Error Goto eh
    
    Dim total As Long
    total = "aa"

Done:
    Exit Sub
eh:
    Debug.Print "Error number: " & Err.Number _
            & " " & Err.Description
End Sub

The Err.Description provides details of the error that occurs. This is the text you normally see when an error occurs e.g. “Type Mismatch”

The Err.Number is the ID number of the error e.g. the error number for “Type Mismatch” is 13. The only time you really need this is if you are checking that a specific error occurred and this is only necessary on rare occasions.

The Err.Source property seems like a great idea but it does not work for a VBA error. The source will return the project name, which hardly narrows down where the error occurred. However, if you create an error using Err.Raise you can set the source yourself and this can be very useful.

Getting the Line Number

The Erl function is used to return the line number where the error occurs.

It often causes confusion. In the following code, Erl will return zero

' https://excelmacromastery.com/
Sub UsingErr()

    On Error Goto eh
    
    Dim val As Long
    val = "aa"

Done:
    Exit Sub
eh:
    Debug.Print Erl
End Sub

This is because there are no line numbers present. Most people don’t realise it but VBA allows you to have line numbers.

If we change the Sub above to have line number it will now print out 20

' https://excelmacromastery.com/
Sub UsingErr()

10        On Error Goto eh
          
          Dim val As Long
20        val = "aa"

Done:
30        Exit Sub
eh:
40        Debug.Print Erl
End Sub

Adding line numbers to your code manually is cumbersome. However there are tools available that will allow you to easily add and remove line numbers to a sub.

When you are finished working on a project and hand it over to the user it can be useful to add line numbers at this point. If you use the error handling strategy in the last section of this post, then VBA will report the line where the error occurred.

Using Err.Raise

Err.Raise allows us to create errors. We can use it to create custom errors for our application which is very useful. It is the equivalent of the Throw statement in JavaC#.

The format is as follows

Err.Raise [error number], [error source], [error description]

Let’s look at a simple example. Imagine we want to ensure that a cell has an entry that has a length of 5 characters. We could have a specific message for this

' https://excelmacromastery.com/
Public Const ERROR_INVALID_DATA As Long = vbObjectError + 513

Sub ReadWorksheet()

    On Error Goto eh
    
    If Len(Sheet1.Range("A1")) <> 5 Then
        Err.Raise ERROR_INVALID_DATA, "ReadWorksheet" _
            , "The value in the cell A1 must have exactly 5 characters."
    End If
    
    ' continue on if cell has valid data
    Dim id As String
    id = Sheet1.Range("A1")
    

Done:
    Exit Sub
eh:
    ' Err.Raise will send code to here
    MsgBox "Error found: " & Err.Description
End Sub

When we create an error using Err.Raise we need to give it a number. We can use any number from 513 to 65535 for our error. We must use vbObjectError with the number e.g.

Err.Raise vbObjectError + 513

Using Err.Clear

Err.Clear is used to clear the text and numbers from the Err.Object. In other words, it clears the description and number.If you want the clear the actual error you can use either On Error GoTo -1 or Resume Next

It is rare that you will need to use Err.Clear but let’s have a look at an example where you might.

In the code below we are counting the number of errors that will occur. To keep it simple we are generating an error for each odd number.

We check the error number each time we go through the loop. If the number does not equal zero then an error has occurred. Once we count the error we need to set the error number back to zero so it is ready to check for the next error.

' https://excelmacromastery.com/
Sub UsingErrClear()

    Dim count As Long, i As Long

    ' Continue if error as we will check the error number
    On Error Resume Next
    
    For i = 0 To 9
        ' generate error for every second one
        If i Mod 2 = 0 Then Error (13)
        
        ' Check for error
        If Err.Number <> 0 Then
            count = count + 1
            Err.Clear    ' Clear Err once it is counted
        End If
    Next

    Debug.Print "The number of errors was: " & count
End Sub

Note 1: Err.Clear resets the text and numbers in the error object but it does not clear the error – see Resume Next Or On Error GoTo -1 for more information about clearing the actual error.

Logging

Logging means writing information from your application when it is running. When an error occurs you can write the details to a text file so you have a record of the error.

The code below shows a very simple logging procedure

' https://excelmacromastery.com/
Sub Logger(sType As String, sSource As String, sDetails As String)
    
    Dim sFilename As String
    sFilename = "C:templogging.txt"
    
    ' Archive file at certain size
    If FileLen(sFilename) > 20000 Then
        FileCopy sFilename _
            , Replace(sFilename, ".txt", Format(Now, "ddmmyyyy hhmmss.txt"))
        Kill sFilename
    End If
    
    ' Open the file to write
    Dim filenumber As Variant
    filenumber = FreeFile 
    Open sFilename For Append As #filenumber
    
    Print #filenumber, CStr(Now) & "," & sType & "," & sSource _
                                & "," & sDetails & "," & Application.UserName
    
    Close #filenumber
    
End Sub

You can use it like this

' Create unique error number
' https://excelmacromastery.com/
Public Const ERROR_DATA_MISSING As Long = vbObjectError + 514

Sub CreateReport()

    On Error Goto eh
    
    If Sheet1.Range("A1") = "" Then
       Err.Raise ERROR_DATA_MISSING, "CreateReport", "Data is missing from Cell A1"
    End If

    ' other code here
Done:
    Exit Sub
eh:
    Logger "Error", Err.Source, Err.Description
End Sub

The log is not only for recording errors. You can record other information as the application runs. When an error occurs you can then check the sequence of events before an error occurred.

Below is an example of logging. How you implement logging really depends on the nature of the application and how useful it will be:

' https://excelmacromastery.com/
Sub ReadingData()
    
    Logger "Information", "ReadingData()", "Starting to read data."
       
    Dim coll As New Collection
    ' add data to the collection
    coll.Add "Apple"
    coll.Add "Pear"
    
    If coll.Count < 3 Then
        Logger "Warning", "ReadingData()", "Number of data items is low."
    End If
    Logger "Information", "ReadingData()", "Number of data items is " & coll.Count
    
    Logger "Information", "ReadingData()", "Finished reading data."

End Sub

Having a lot of information when dealing with an error can be very useful. Often the user may not give you accurate information about the error that occurred. By looking at the log you can get more accurate information about the information.

This section covers some of the other Error Handling tools that VBA has. These items are considered obsolete but I have included them as they may exist in legacy code.

Error Function

The Error Function is used to print the error description from a given error number. It is included in VBA for backward compatibility and is not needed because you can use the Err.Description instead.

Below are some examples:

' Print the text "Division by zero"
Debug.Print Error(11)
' Print the text "Type mismatch"
Debug.Print Error(13)
' Print the text "File not found"
Debug.Print Error(53)

Error Statement

The Error statement allows you to simulate an error. It is included in VBA for backward compatibility. You should use Err.Raise instead.

In the following code we simulate a “Divide by zero” error.

' https://excelmacromastery.com/
Sub SimDivError()

    On Error Goto eh
        
    ' This will create a division by zero error
    Error 11
    
    Exit Sub
eh:
    Debug.Print Err.Number, Err.Description
End Sub

This statement is included in VBA for backward compatibility. You should use Err.Raise instead.

A Simple Error Handling Strategy

With all the different options you may be confused about how to use error handling in VBA. In this section, I’m going to show you how to implement a simple error handling strategy that you can use in all your applications.

The Basic Implementation

This is a simple overview of our strategy

  1. Place the On Error GoTo Label line at the start of our topmost sub.
  2. Place the error handling Label at the end of our topmost sub.
  3. If an expected error occurs then handle it and continue.
  4. If the application cannot continue then use Err.Raise to jump to the error handling label.
  5. If an unexpected error occurs the code will automatically jump to the error handling label.

The following image shows an overview of how this looks

error-handling

The following code shows a simple implementation of this strategy:

' https://excelmacromastery.com/
Public Const ERROR_NO_ACCOUNTS As Long = vbObjectError + 514

Sub BuildReport()

    On Error Goto eh
    
    ' If error in ReadAccounts then jump to error
    ReadAccounts
    
    ' Do something with the code
    
Done:
    Exit Sub
eh:
    ' All errors will jump to here
    MsgBox Err.Source & ": The following error occured  " & Err.Description
End Sub

Sub ReadAccounts()
    
    ' EXPECTED ERROR - Can be handled by the code
    ' Application can handle A1 being zero
    If Sheet1.Range("A1") = 0 Then
        Sheet1.Range("A1") = 1
    End If
    
    ' EXPECTED  ERROR - cannot be handled by the code
    ' Application cannot continue if no accounts workbook
    If Dir("C:DocsAccount.xlsx") = "" Then
        Err.Raise ERROR_NO_ACCOUNTS, "UsingErr" _
                , "There are no accounts present for this month."
    End If

    ' UNEXPECTED ERROR - cannot be handled by the code
    ' If cell B3 contains text we will get a type mismatch error
    Dim total As Long
    total = Sheet1.Range("B3")
    
    
    ' continue on and read accounts
    
End Sub

This is a nice way of implementing error handling because

  • We don’t need to add error handling code to every sub.
  • If an error occurs then VBA exits the application gracefully.

A Complete Error Handling Strategy

The above strategy has one major drawback. It doesn’t provide any information about the error. It is better than having no strategy as it prevents the application crashing. But that is the only real benefit.

VBA doesn’t fill Err.Source with anything useful so we have to do this ourselves.

In this section, I am going to introduce a more complete error strategy. I have written two subs that perform all the heavy lifting so all you have to do is add them to your project.

The purpose of this strategy is to provide you with the Stack* and line number when an error exists.

*The Stack is the list of sub/functions that were currently in use when the error occurred.

This is our strategy

  1. Place error handling in all the subs.
  2. When an error occurs, the error handler adds details to the error and raises it again.
  3. When the error reaches the topmost sub it is displayed.

We are simply “bubbling” the error to the top. The following diagram shows a simple visual of what happens when an error occurs in Sub3

Error Handling - bubbling

The only messy part to this is formatting the strings correctly. I have written two subs that handle this, so it is taken care of for you.

There are the two helper subs, RaiseError and DisplayError. You can download the library below:

An Example of using this strategy

Here is a simple coding example that uses these subs. In this strategy, we don’t place any code in the topmost sub. We only call subs from it.

' https://excelmacromastery.com/
Sub Topmost()

    On Error Goto EH
    
    Level1

Done:
    Exit Sub
EH:
    DisplayError Err.source, Err.Description, "Module1.Topmost", Erl
End Sub

Sub Level1()

    On Error Goto EH
    
    Level2

Done:
    Exit Sub
EH:
   RaiseError Err.Number, Err.source, "Module1.Level1", Err.Description, Erl
End Sub

Sub Level2()

    On Error Goto EH
    
    ' Error here
    Dim a As Long
    a = "7 / 0"

Done:
    Exit Sub
EH:
    RaiseError Err.Number, Err.source, "Module1.Level2", Err.Description, Erl
End Sub

The result looks like this:

error handling output

If your project has line numbers the result will include the line number of the error:

error handling output line

Error Handling in a Nutshell

  • Error Handling is used to handle errors that occur when your application is running.
  • You write specific code to handle expected errors. You use the VBA error handling statement On Error GoTo [label] to send VBA to a label when an unexpected error occurs.
  • You can get details of the error from Err.Description.
  • You can create your own error using Err.Raise.
  • Using one On Error statement in the top most sub will catch all errors in subs that are called from here.
  • If you want to record the name of the Sub with the error, you can update the error and rethrow it.
  • You can use a log to record information about the application as it is running.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

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

  • Коды ошибок атол 22 птк
  • Коды ошибок аристон avsl 800
  • Коды ошибок астра н автомат
  • Коды ошибок в gta san andreas
  • Коды ошибок аристон aqsl 85

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

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