Vba ошибка code execution has been interrupted

Хитрости »

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


Иногда при выполнении вполне рабочего кода может возникнуть ошибка «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
ссылки
статистика

I first came across this Microsoft Excel vba error back in 2009, when the vba dialog box interrupted macro processing with the message «Code Execution Has Been Interrupted» and it quite literally did my head in.

It’s a weird error because it doesn’t have an error number and in fact it isn’t really an error but rather a bug for which a lot of misinformation existed on the net back then.

The Problem defined.

You’ve written your Excel VBA application and everything’s working fine, then for no apparent reason the following dialog box pops up, you click «Debug» on the dialog box but you cannot find anything wrong with your code.

Code Execution Has Been Interrupted

Maybe it’s a one off and you run the code again, but the message «Code Execution Has Been Interrupted» appears again, oops!

When that happened to me, after a lot of research on the net, I thought I was up a certain creek without a paddle.

Since my application was going to be deployed to my user base, I couldn’t have something as unprofessional as this dialog box popping up randomly.

The code would go into break mode at various parts of the program even though no «break points» or «STOP» commands existed on those lines.

What I think causes it

I can only guess at this, not being a Microsoft Insider, but it seems to me that when you set breakpoints in your code, either by using the «STOP» command or clicking the left sidebar of the code or hitting «ctrl» + «break» to enter break mode during your development process, Microsoft Excel sometimes records this «behind the scenes» and doesn’t clear the breakpoint out of it’s «memory».

So the breakpoint somehow gets hardcoded into your vba module within the file even though there’s no visible breakpoint in your visual basic editor.

The Solution – Clear the hidden break in the code with another «Ctrl + Break»

So when this happens to you, click «Debug» on the Microsoft VBA «Code Execution Interrupted» dialog box, this’ll jump you to the Visual Basic Editor and a particular line of code will be highlighted to show that execution has stopped at that point.

As the compiled vba code in the workbook probably has a hidden breakpoint saved at this point, just hit «Ctrl + Break» on your keyboard (I tend to do Ctrl+Break multiple times).

Sign up below and get notified when new Business Programmer blog or video tutorials are created.

This removes the hidden breakpoint and all you need to do now is save the workbook and your problem is solved, at least for that breakpoint.

If this problem does occur again, most likely you’ve multiple hidden breakpoints in your application.

Just rinse and repeat the above instructions for each instance of «Code Execution Interrupted» until the problem is solved.

Note do not use Application.EnableCancelKey = xlDisabled as this doesn’t solve the problem and in fact ensures that you cannot «Break» into the application if something goes wrong.

Reader Interactions

Сегодня меня опять начало доставать это сообщение
и на одном зарубежном сайте я все-таки нашел решение (без перезагрузки компьютера и 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.

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

TLDR

Open the module with the problem and press the following keystrokes:

  • ctrl+home to go to the top of the module
  • ' to add a comment in front of Option Explicit
  • down to parse all without Option Explicit and tell VBA that all needs to be recompiled
  • up
  • backspace to uncomment
  • alt+d
  • l to trigger the recompilation of the whole module

The solution described above assumes the modules in the VBA project use Option Explicit, (which they should, it is very good practice). If your modules do not use it, then, instead of commenting and uncommenting the first line, you can select all the code, cut it and paste it back.

The details

This problem is caused by something going wrong with the incremental compilation.

When a module is edited, VBA compiles only the modified functions, not the whole project. Sometimes things go wrong with the incremental compilation and two things can happen at execution time: phantom breakpoints like the one mentioned here appear or errors about undefined or wrong type variables show up.

The answers that mention modifying one line often help, because they do trigger the compilation of the function containing that line, which in turn may trigger the compilation of other functions or even the entire project. But the problem sometimes pops back up because editing one line only may not trigger the compilation of the whole project.

The answer with the highest number of upvotes may help, but it requires first to reproduce the problem, which sometimes doesn’t reproduce on the development machine.

The correct solution is to force the recompilation of the whole project.

I don’t think there is an explicit way to do so, but it is possible to force the recompilation of the largest module, one that is used by or uses all modules and classes. There is no command to trigger such recompilation, but by changing one global directive will do the job.

In some cases it may be necessary to repeat the steps in multiple modules.

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Понравилась статья? Поделить с друзьями:
  • Vba ошибка 462
  • Vba обработка ошибок on error
  • Vcurentime140 dll ошибка
  • Vba ошибка 459
  • Vba код ошибки 400