Хитрости »
12 Апрель 2016 22837 просмотров
Иногда при выполнении вполне рабочего кода может возникнуть ошибка «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
ссылки
статистика
Сегодня меня опять начало доставать это сообщение
и на одном зарубежном сайте я все-таки нашел решение (без перезагрузки компьютера и 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.
Позже постараюсь перевести.
{quote}{login=Лузер™}{date=07.12.09 08:46}{thema=}{post}Я сразу не заметил этого:
CEHDI
End Sub
Оно специально?
У меня ошибка 28: Out of stack space{/post}{/quote}Да, специально. Т.к. сообщение об ошибке «code execution has been interrupted» возникало не при каждом запуске кода, вот и написал пример с бесконечным зацикливанием. Естественно, что при удачном раскладе (если б не «code execution…»), места в стеке не остаётся и получаем ошибку 28.
Два часа перезагружал комп, но всё-таки избавился от глюка.
Первое, что я сделал: Пуск -> Выполнить -> msconfig -> Обычный запуск
Потом перепрятал вот это:
<MVS2010>Visual Studio Tools for Officex86VSTOExcelAdaptor.dll
<MVS2010>Common7IDEPrivateAssembliesTFSOfficeAdd-in.dll
После перезагрузки и запуска Excel, вернул драйверы на место.
Сообщение об ошибке выпрыгивать перестало, но неудаляемые ссылки в ранее созданных книгах на Microsoft Forms 2.0 так и остались. Эта ссылка появлялась совершенно необоснованно: создаёшь книгу, пишешь пару строк кода, закрываешь с сохранением, открываешь – она там, хотя UserForm ни разу не пробегала. Ладно, перетащил данные в новые книги – и всё ОК.
Кстати, заодно избавился ещё от одного глюка, опять же, как выяснилось, из-за нового Visual Studio, – странного поведения того же редактора VBA, но в Excel 2007: это вообще жесть была…
Начинаешь писать код и он сразу же, прямо вслед за каждым символом подсвечивает неправильный ввод красным, а не после ввода всей строки. Но это мелочи по сравнению с тем, что не вводится пробел. Нажимаешь Space – он стирается как если бы нажали BS. Но если вслед за Space успеть быстро нажать следующий символ, тогда он останется жив – бред, короче. Что-то там ещё пыталось дописываться автоматом: медвежьи услуги какие-то.
Глюк ушёл вместе с удалением:
<MVS2010>Common7/IDE/PrivateAssemblies/Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto
— 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.
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.