Ошибка vba code execution has been interrupted

Хитрости »

12 Апрель 2016              22868 просмотров


Иногда при выполнении вполне рабочего кода может возникнуть ошибка «Code execution has been interrupted«:
Code execution has been interrupted
чаще всего она появляется в циклах (это Do … Loop, For each, For … Next). Но может проявится и на отдельных участках кода совершенно независимо от того, что делает тот или иной кусок кода. Сама по себе ошибка не является таковой — при нажатии Continue код продолжает работать и может даже дойти до конца уже без ошибок. Но что примечательно — появившись в каком-то коде однажды, эта ошибка начинает преследовать вас и при этом воспроизводится только на том ПК, на котором появилась. На других же ПК код может работать отлично и без всяких казусов.

Почему вообще появляется эта ошибка? Точный ответ на этот вопрос я, к сожалению, не дам. Только предположения: VBA тоже хранит всевозможные логи при работе и обращается к разным библиотекам. И скорее всего в какой-то момент этого хлама набирается так много, что VBE начинает «подглючивать» таким вот нестандартным образом, предполагая, что мы пытаемся выполнить параллельно два кода.

И главное: как ошибку Code execution has been interrupted устранить?
Я знаю два способа.
Способ 1 — разовый
Перед выполнением кода поставить строку:

Application.EnableCancelKey = xlDisabled

а после выполнения(перед End Sub или в любом месте, где может произойти выход из процедуры) её вернуть:

Application.EnableCancelKey = xlInterrupt

чем не нравится данный метод мне лично: свойство EnableCancelKey отвечает за возможность обработки нажатия клавиш при выполнении кода. Значение xlDisabled переводит VBA в режим «глухой обороны» — т.е. он не будет реагировать ни на какие нажатия пока не завершится выполнение кода. Догадались, чем это чревато? Правильно: если вдруг попали в бесконечный цикл или захотели прервать выполнение — ничего не получится, т.к. сочетание Ctrl+Break будет просто проигнорировано.


Способ 2 — пожизненный(почти)

После появления ошибки нажмите

Debug

, затем

Ctrl

+

Break

, затем кнопку

Play

на панели редактора VBE (зеленый треугольничек воспроизведения кода) — продолжится выполнение кода. После этого ошибка должна исчезнуть.
Главное жать не

F5

для продолжения выполнения, а именно треугольник на панели. Иначе может не сработать.


Если знаете еще способы устранения ошибки — делитесь в комментариях — это обязательно поможет кому-то спасти нервы и силы и в карму вам плюсанется :)


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

From what I can see on the web, this is a fairly common complaint, but answers seem to be rarer. The problem is this:

We have a number of Excel VBA apps which work perfectly on a number of users’ machines. However on one machine they stop on certain lines of code. It is always the same lines, but those lines seem to have nothing in common with one another.

If you press F5 (run) after the halt, the app continues, so it’s almost like a break point has been added. We’ve tried selecting ‘remove all breaks’ from the menu and even adding a break and removing it again.

We’ve had this issue with single apps before and we’ve ‘bodged’ it by cutting code out of modules, compiling and then pasting it back in etc.

The problem now seems to relate to Excel itself rather than a single .xls, so we’re a little unsure how to manage this.

Permalink

Cannot retrieve contributors at this time

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

Code execution has been interrupted

vblr6.chm1011317

vblr6.chm1011317

office

daf08b53-6875-e63c-a5d1-9f1fbfee7470

06/08/2017

high

Code execution can be suspended when necessary. This condition has the following cause and solution:

  • A CTRL+BREAK (Microsoft Windows), ESC (Microsoft Excel) or COMMAND+PERIOD (Macintosh) key combination has been encountered. In the error dialog box, click Debug to enter break mode, Continue to resume, or End to stop execution.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

[!includeSupport and feedback]

Сегодня меня опять начало доставать это сообщение
и на одном зарубежном сайте я все-таки нашел решение (без перезагрузки компьютера и Excel-я),
которое мне помогло.

Итак, если Вы получили сообщение «Code Execution has been interrupted»
нажмите «Debug», затем Ctrl+Break, затем кнопку «Play» на панеле редактора VBE — продолжение выполнения кода.
Больше ошибка не появлялась ни в текущей сессии, ни после перезагрузки приложения.

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

На английском:

— Some manual actions:
“Just hit f5 or press ‘continue’ till the end of the run.

“When the code is interrupted… Click to debug the code and then hit ctrl + break.

— Application.EnableCancelKey actions.
“At the start of your code: Application.EnableCancelKey = xlDisabled (For Excel) or Application.EnableCancelKey = wdCancelDisabled (For Word) .”

“Sub X ; Application.EnableCancelKey = XlEnableCancelKey.xlDisabled; Code; Application.EnableCancelKey = XlEnableCancelKey.xlInterrupt.); End Sub.”

But: “When the macro finishes, the setting will be reset to it’s default (even if you don’t specify) so there is no need to change the setting back.”

— Stop your worksheet from updating your links, while running macros.
For example when an add-in updated a price on the sheet it would give the above error. He deleted the link from edit links.)

— Service packs.

Remove them i.e. work on windows, before certain service pack is installed.

Save Excel files in between PC’s with differing service packs

— Tools | Options | Security Tab | Macro Security button = medium

— Simply copy & paste code.
“deleting all code, saving, and then reinserting code seems to help some people”

“cutting code out of modules, compiling and then pasting it back in etc.”

“In order to actually trigger a rebuild, it is normally necessary to modify a line, and then move the cursor to the next line to flag the source code as modified (e.g. make a change, move cursor down, move cursor up and undo the change manually).”

— Reboot PC

— Repair and cleanup actions: ((As a layman I myself am scared of this though))

Worked apparently: “I copied the workbook in windows explorer and I tried the «Repair Office» utility.”

Didn’t help much it seems: Run Office’s “detect and repair”. Forgive my ignorance: Are they talking here about [Control panel configuration manager components repair]?

“Google around on VBA Code Cleaners”

Worked it looks: “This problem got solved by choosing REPAIR in Control Panel. I guess this explicitly re-registers some of Office’s native COM components and does stuff that REINSTALL doesn’t. I expect the latter just goes through a checklist and sometimes accepts what’s there if it’s already installed, maybe. I then had a separate issue with registering my own .NET dll for COM interop on the user’s machine (despite this also working on other machines) though I think this was my error rather than Microsoft. Thanks again, I really appreciate it.”

Attempt, didn’t work I think: “The usual things — Run Rob Bovey’s VBA Code Cleaner on your VBA Code — remove all addins on the users PC, particularly COM and .NET addins — Delete all the users .EXD files (MSoft Update incompatibilities) — Run Excel Detect & Repair on the users system — check the size of the user’s .xlb file (should be 20-30K) — Reboot then delete all the users Temp files.”

— Re-install Excel

— MS Access : you open the .mdb file via a shortcut with the /decompile option (an undocumented option).

— Of course a good habit anyway is to always put ‘option explicit’ at the top of all your VBA subs. (It happens automatically if you choose [tools options require variable checking].) But this did not help us with the problem.

Позже постараюсь перевести.

— Some manual actions:
“Just hit f5 or press ‘continue’ till the end of the run.

“When the code is interrupted… Click to debug the code and then hit ctrl + break.

— Application.EnableCancelKey actions.
“At the start of your code: Application.EnableCancelKey = xlDisabled (For Excel) or Application.EnableCancelKey = wdCancelDisabled (For Word) .”

“Sub X ; Application.EnableCancelKey = XlEnableCancelKey.xlDisabled; Code; Application.EnableCancelKey = XlEnableCancelKey.xlInterrupt.); End Sub.”

But: “When the macro finishes, the setting will be reset to it’s default (even if you don’t specify) so there is no need to change the setting back.”

— Stop your worksheet from updating your links, while running macros.
For example when an add-in updated a price on the sheet it would give the above error. He deleted the link from edit links.)

— Service packs.

Remove them i.e. work on windows, before certain service pack is installed.

Save Excel files in between PC’s with differing service packs

— Tools | Options | Security Tab | Macro Security button = medium

— Simply copy & paste code.
“deleting all code, saving, and then reinserting code seems to help some people”

“cutting code out of modules, compiling and then pasting it back in etc.”

“In order to actually trigger a rebuild, it is normally necessary to modify a line, and then move the cursor to the next line to flag the source code as modified (e.g. make a change, move cursor down, move cursor up and undo the change manually).”

— Reboot PC

— Repair and cleanup actions: ((As a layman I myself am scared of this though))

Worked apparently: “I copied the workbook in windows explorer and I tried the «Repair Office» utility.”

Didn’t help much it seems: Run Office’s “detect and repair”. Forgive my ignorance: Are they talking here about [Control panel configuration manager components repair]?

“Google around on VBA Code Cleaners”

Worked it looks: “This problem got solved by choosing REPAIR in Control Panel. I guess this explicitly re-registers some of Office’s native COM components and does stuff that REINSTALL doesn’t. I expect the latter just goes through a checklist and sometimes accepts what’s there if it’s already installed, maybe. I then had a separate issue with registering my own .NET dll for COM interop on the user’s machine (despite this also working on other machines) though I think this was my error rather than Microsoft. Thanks again, I really appreciate it.”

Attempt, didn’t work I think: “The usual things — Run Rob Bovey’s VBA Code Cleaner on your VBA Code — remove all addins on the users PC, particularly COM and .NET addins — Delete all the users .EXD files (MSoft Update incompatibilities) — Run Excel Detect & Repair on the users system — check the size of the user’s .xlb file (should be 20-30K) — Reboot then delete all the users Temp files.”

— Re-install Excel

— MS Access : you open the .mdb file via a shortcut with the /decompile option (an undocumented option).

— Of course a good habit anyway is to always put ‘option explicit’ at the top of all your VBA subs. (It happens automatically if you choose [tools options require variable checking].) But this did not help us with the problem.

Понравилась статья? Поделить с друзьями:
  • Ошибка uplay r1 loader64 dll для far cry 4
  • Ошибка vba can not find project or library
  • Ошибка uplay r1 loader dll для
  • Ошибка variable sized object may not be initialized
  • Ошибка uplay r1 dll скачать