Excel VBA App stops spontaneously with message "Code execution has been halted" - excel

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.
Any help would be gratefully received :)
Thanks,
Philip Whittington

I have found a 2nd solution.
Press "Debug" button in the popup.
Press Ctrl+Pause|Break twice.
Hit the play button to continue.
Save the file after completion.

One solution is here:
The solution for this problem is to add the line of code
“Application.EnableCancelKey = xlDisabled” in the first line of your
macro.. This will fix the problem and you will be able to execute the macro
successfully without getting the error message “Code execution has been interrupted”.
But, after I inserted this line of code, I was not able to use Ctrl+Break any more. So it works but not greatly.

This problem comes from a strange quirk within Office/Windows.
After developing the same piece of VBA code and running it hundreds of times (literally) over the last couple days I ran into this problem just now. The only thing that has been different is that just prior to experiencing this perplexing problem I accidentally ended the execution of the VBA code with an unorthodox method.
I cleaned out all temp files, rebooted, etc... When I ran the code again after all of this I still got the issue - before I entered the first loop. It makes sense that "press "Debug" button in the popup, then press twice [Ctrl+Break] and after this can continue without stops" because something in the combination of Office/Windows has not released the execution. It is stuck.
The redundant Ctrl+Break action probably resolves the lingering execution.

I found hitting ctrl+break while the macro wasn't running fixed the problem.

I would try the usual remedial 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

I have came across this issue few times during the development of one complex Excel VBA app. Sometimes Excel started to break VBA object quite randomly. And the only remedy was to reboot machine. After reboot, Excel usually started to act normally.
Soon I have found out that possible solution to this issue is to hit CTRL+Break once when macro is NOT running. Maybe this can help to you too.

Thanks to everyone for their input. 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.

I have had this problem also using excel 2007 with a foobar.xlsm (macro enabled ) workbook which would get the "Code execution has been interrupted" by simply trying to close the workbook on the red X in the right corner with no macros running at all, or any "initialize" form, workbook, or workheet macros either. The options I got were "End" or "Continue", Debug was always greyed out. I did as a previous poster suggested Control Panel->Programs and Features-> right click "Microsoft Office Proffesional 2007" (in my case) ->change->repair.
This resolved the problem for me.
I might add this happened soon after a MS update and I also found an addin in Excel called "Team Foundation" from Microsoft which I certainly didnt install voluntarily

I would like to add more details to Stan's answer #2 for below reasons:
I faced this issue myself more than dozen times and depending on project conditions, I chose between stan's voodoo magic answer #1 or #2. When I kept on facing it again, I become more inquistive that why it happens in first place.
I'd like to add answer for Mac users too.
There are limitations with both these possible answers:
if the code is protected (and you don't know password) then answer #1 won't help.
if the code is unprotected then answer #2 won't let you debug the code.
It may happen due to any of the below reasons:
Operating system not allocating system resources to the Excel process. (Solution: One needs to just start the operating system - success rate is very low but has known to work many times)
P-code is the intermediate code that was used in Visual Basic (before .NET) and hence it is still used in the VBA. It enabled a more compact executable at the expense of slower execution. Why I am talking about p-code? Because it gets corrupted sometimes between multiple executions and large files or just due to installation of the software (Excel) went corrupt somewhere. When p-code corrupts. the code execution keeps getting interrupted. Solution: In these cases, it is assumed that your code has started to corrupt and chances in future are that your Excel workbook also get corrupt giving you messages like "excel file corrupted and cannot be opened". Hence, as a quick solution, you can rely on answer #1 or answer #2 as per your requirements. However, never ignore the signs of corruption. It's better to copy your code modules in notepad, delete the modules, save & close the workbook, close the excel. Now, re-open the workbook and start creating new modules with the code copied earlier to notepad.
Mac users, try any of the below option and of them will definitely work depending on your system architecture i.e. OS and Office version
Ctrl + Pause
Ctrl + ScrLk
Esc + Esc (Press twice consecutively)
You will be put into break mode using the above key combinations as the macro suspends execution immediately finishing the current task. This is replacement of Step 2.
Solution: To overcome the limitation of using answer #1 and answer #2, I use xlErrorHandler along with Resume statement in the Error Handler if the error code is 18. Then, the interrupt is sent to the running procedure as an error, trappable by an error handler set up with an On Error GoTo statement. The trappable error code is 18. The current procedure is interrupted, and the user can debug or end the procedure. Microsoft gives caution that do not use this if your error handler has resume statement else your error handler always returns to the same statement. That's exactly we want in unwanted meaningless interruptions of code execution.

My current reputation does not yet allow to post this as a comment.
Stans solution to enter the debug mode, press twice Ctrl+Break, play on, save did solve my problem, but I have two unexpected twists:
My project struture is password protected, so in order to get into the Debug Mode I had to first enter Developer mode, click on the project structure and enter the password.
My project is a template file (.xmtl). I opened the file via double click which opens it as .xml with a "1" at the end of the previous file name. I fixed the bug as by Stans instruction and saved it as that ...1.xml file. When I then opened the template again, this time as template, and wanted to apply the same bug fix to that file, the bug was gone! I did not change this file and still no bug at executing the Macro. This means to me that the bug is not actually in the file, but in a (hidden) setting in Excel.

If it's a phantom breakpoint:
1 Delete the offending line of code
2 Run the code again
3 Repaste the line
I found this laughably simple solution after spending a couple days wading through all the answers here and elsewhere. I figured, if I link it to my original question it might help some other poor chap, since the question it's on is VBA break execution when there's no break key on keyboard and this is more applicable.
Link to original answer

I faced the same issue today. Resolved it with these steps.
Create a new module
Move the procedure that is causing the issue to this new module.
Save project
Run macro again.
This time, the code execution will run till completion without any intermediate stops.

Related

Excel crashes when loading file that contains userform

Excel crashes when opening files that contain a userform
This is a known problem with a known solution workaround which is to delete a file called Excel.box from here:
C:\Users\SlowLearner\Application Data\Microsoft\Forms\Excel.box
According to this forum post the purpose of the Excel.box (& Word.box) file is:
Files such as Winword.box and Excel.box are associated with the
Control Toolbox you see when you are designing a UserForm in the
Visual Basic editor. The files contain information about the layout of
the Control Toolbox (additional tab pages, controls that have been
added or removed, custom icons, ...) If a user has never modified the
Control Toolbox in any way, there will probably be no .box file. By
deleting a .box file, you will restore the Control Toolbox to its
default (factory preset) configuration - this is the only way to do
that. Sometimes, the .box file becomes corrupted and must be deleted.
There are no negative side effects to deleting it.
Unfortunately Excel.box returns :(
It would seem that for most users the problem is fixed by deleting the file, sadly not for me.
I'd like to understand what is causing this problem to recur. A few points to note:
this (touch wood) is not impacting MS Word on my PC
I am using Office 2010, 64 bit version on Win10
I have not made any conscious change to form settings
if I delete the file > start Excel > UN-DELETE the file: everything works :-/
some other experiences with this issue here
For the time being I'll just check for and delete the file before launching Excel, but this is hardly an acceptable solution for the long term. Appreciate thoughts for a proper fix... TIA
Additional Information:
I have not fully explored the crash but so far it happens when:
starting the application by opening an xl?.m file with a userform
application does not get past the splash screen
crashes with the application's CRASH screen (... encounted an error...)
starting the application with a blank worksheet then adding a userform
crashes immediately with the applications CRASH screen displayed (see below)
The above crash happened after rebooting my PC, had a chance to explore it some more.
First I opened the file I had been working on (contains userforms):
annoyingly it opened without crashing
I did NOT enter the IDE
I closed the file (Excel closed normally)
Then I created a new worksheet
I opened the VBA IDE
right-click 'add UserForm' - Excel crashed immediately
(I aborted the recovery / search for a solution attempt)
Then I re-opened the file I had been working on
opened the VBA IDE (the project is PW protected)
the very instant that I entered the PW and hit enter Excel crashed
crash was same both times...
Safe Mode:
Crash still happens in safe mode - steps to reproduce:
Run: Excel /safe
Open VBA IDE
r-click add userform
crashes immediately
Creation of the EXCEL.box file
Based on visually observing the folder which had the Excel.box file I did some tests to try and see when it was created. Basically it seems to appear when one of the following happens:
- the UserForm tools box is closed
- the IDE is closed (after showing the userform)
I've also now tried to modify the userform toolbox by removing everything from it. Excel is still crashing after every restart of the application (which is odd as I was not able to crash it like that earlier).
Office Repair - not tested (yet)
Reluctant to try Office Repair as based on the following quote from here (scroll down: pg 1 reply 8 by Steve IT) I'm not expecting it to work :-/ (but will try if no other suggestions surface).
Thanks for the continued suggestions, however I have tried a repair and also removed Visual Studio 2013 and Office altogether (just in case VS was interfering) and reinstalled both, but it still throws the errors reported previously.
Other user profiles
Created a brand new user called 'test'. Test has the exact same problem.
This problem eventually resolved itself, not sure why. I continued to use Excel normally and it continued to crash so I would delete the offending .box file and start over...
As of Nov 2017 Excel no longer crashes with respect to this issue; my best guess is there was an automatic update that resolved the issue.
Looks like this issue still occurs and it is not just limited to Excel but also Powerpoint.
The fix as mentioned above works where you move / delete any files in the below folder location resolves the issue.
C:\Users\%username%\Application Data\Microsoft\Forms
It is highly likely that this error is caused by bad code in a macro or an Add-In that uses forms. The problem is replicating this can be difficult so you have to debug this in some way when it does crash out.
POWERPNT.box
EXCEL.box
are some of the files that get generated, where Excel or Powerpoint crash on the splash screen.
Try adding the command
ThisWorkbook.VBProject.VBComponents("UserForm").Activate
just before your
"UserForm".Show line.

What causes 'can't find project or library error' and how to prevent it from happening?

I'm having an issue with tool I developed in excel for one of our offices. It is a big enough file with couple of macros in it, but it works smooth day to day.
However every few days file will through error 'Can't find project or library' and file will crash. I know the standard guides are that when this error appears, it is to go to vba>tools>referneces and uncheck the missing library, however this is not the case in here. Simply when this happens file crashes and restarts and if it will happen once, every other attempt to open back the file will result in same error in crash. I mean file can be absolutely fine, you will save it, go back to it and error happens. So I always have to recover the file which absolutely destroys it, however I can at least recover from it information uploaded there by the users and copy it into the template.
So 2 questions I have is what is causing this to happen? Both myself and the other office are using the same version of excel so compatibility should not be an issue.
2 questions is is there anything that can be done to prevent this error from happening.
I have exactly this problem. As stated, once the error occurs, it it results in a permanent "unfixable" loop. I use powerquery and linked data and this appears to randomly "damage" the file as described - most frequently when excel crashes for some reason.
I have found either of the following to work:
- Open the file on a different computer that is not on the LAN. This
appears to be a key requirement.
- Open the file with "Excel Online"
In each case, simply open the file and save it with a new name. Move the new file back to the work PC and it will once more open perfectly.
On rare occasions (if powerquery is in use), it is necessary to "refresh all" data connections before saving the new file.
As a bonus, the new file is often smaller than the original.
This worked for me:
In VB go to Tools » References
1) Uncheck the library "Crystal Analysis Common Controls 1.0". Or any library.
Just leave these 5 references:
1) Visual Basic For Applications (This is the library that defines the VBA language.)
2) Microsoft Excel Object Library (This defines all of the elements of Excel.)
3) OLE Automation (This specifies the types for linking and embedding documents and for automation of other applications and the "plumbing" of the COM system that Excel uses to communicate with the outside world.)
4) Microsoft Office (This defines things that are common to all Office programs such as Command Bars and Command Bar controls.)
5) Microsoft Forms 2.0 This is required if you are using a User Form. This library defines things like the user form and the controls that you can place on a form.
Then Save.
I've had similar nasty issues.
First thing to do is use the CodeCleaner a free utility from AppsPro
This will export your modules and then re-import them, because internally they get a lot of binary "lint" which can cause problem.
Second thing to suggest is start breaking up your code base. So start removing modules to see which module is the offender. Horrible I know but how can you tell otherwise where the problem is.
Third suggestion is to always fully qualify your functions. So instead of Len(sMyString) write VBA.Len(sMyString) that helps prevent false negative compile errors.

Can't enter break mode at this time

This has been happening increasingly, when I have a sheets.add or sheets.delete in excel VBA. After searching and searching I finally found the official Microsoft support page on it. My question is, does anyone know why I could have stepped through this code just fine over and over, and then all of a sudden it starts doing what Microsoft says it would always do, and is there a way to fix it?
Sub foo()
Sheets.add
debug.print "sheet added" 'breakpoint here
End sub
It's as simple as that. You won't be able to recreate it, because the issue I'm asking about is the fact that it doesn't happen at first. It works just fine over and over then randomly presents the error described in the linked Microsoft support page.
Check if Microsoft Visual Basic for Applications Extensibility is being referenced in the project.
You can check that in the Tools/References Menu on the Visual Basic window of the project.
Referencing Visual Basic for Applications Extensibility prevents the program having its execution suspended:
Excel helps says specifically:
A change was made programmatically to the project using the extensibility (add-in) object model. This prevents the program from having execution suspended. You can continue running, or end execution, but can't suspend execution.
You are unable to step through code when making changes to the project (dynamically eg using InsertLine etc). the code can be run but not stepped through.
Deleting certain objects including ActiveX objects actually changes the VB project. It took me some time to realize that the following line of code prevented the VBE from entering break mode:
Excel.ActiveSheet.DrawingObjects.Delete
If you can identify the code causing the issue, and the order of operations isn't important, move it to the end of your script.
Here are a few suggestions which are not fool-proof,
Firstly, verify that the error does not occur if a breakpoint is not set.
If it doesn't, try a few other things:
From the VBE Debug menu, "Compile VBA Project", it's worth a shot.
Delete the line entirely. Run the code. Then put the line back in and try again with the breakpoint.
Add a DoEvents statement after the Sheets.Add
Use a MsgBox instead of a breakpoint on a Debug.Print. With the message box displayed, attempt to manually break using ctrl+fn+End. (At this point, "breaking" isn't necessary but it would be interesting to see whether you can break this way)
Put a breakpoint on Sheets.Add instead; practically speaking, there's no reason to put the breakpoint on a Print statement if you can just put it on the preceding line.
Are there any Addins? If so, disable all of them and re-enable one at a time, testing to see which one may contribute to the error.
Yet another Excel/VBA glitch.
When it happens to me when I click a button running a macro:
I first try to directly run the macro from VBE,
if it fails, then I put a breakpoint at the first instruction of the macro,
if it still fails, I try both,
or, after clicking the button and breaking on the first breakpoint, I do a single step (SHIFT F8) and then I can let debug run freely as usual (F5).
And so far I don't get this error anymore.
Probably not foolproof either but worth a try.
Ran into the same issue, and (as far as I can tell) the only relevant answer here is Answer 5 (i.e. the one provided by Chrisb).
I've been working with vba for (too many) years now, and never encountered this until I had a project that needed vba to delete ActiveX controls. In my case, the 'ActiveX controls' were a spurious result of data copied in from a web page.
Additionally, there appears to be a way around the issue. Using the following code (versus, e.g. deleting the ActiveX as a shape), seems to circumvent the issue:
On Error Resume Next
ActiveSheet.OLEObjects.Visible = True
ActiveSheet.OLEObjects.Delete
On Error GoTo 0
I say 'appears' and 'seems' above as implementing the above solved the issue for me. However, before I implemented same, I had made other code changes and I have not yet fully regression tested for all possible other reasons the problem was resolved. :)
This has happened to me multiple times and this solution works for me.
Run a different macro within the same VBA project.
Then go back and run the same macro that is causing the pop-up message to appear. The message should no longer appear.

Excel 2007 VBA Macro Stops when userform called

I've been building a macro for a few weeks, and all of a sudden part doesn't work properly. When I try to call a userform via .Show, for some reason the marco stops running right there and then, and highlights the ".show" line. (Even if I jump to the userform box, the buttons are not functional.) If I press F5 it starts to run again, but I obviously don't want the code to stop running in the middle of the program. Any idea why this could happen, especially when it didn't used to happen?
It turns out I had a bug in my code, which was hiding because I did not remove a previous "On Error Resume Next." Many thanks to Siddharth!
It is possible that the OP's concluded answer is not connected to the question, but is coincidental.
I had the same thing. Code stopped on frm.show for aboluteamente no legitimate reason. It was as though there was a Stop there. I tried everything but the solution was, unequivocably, to reboot.
I know it's a level one answer, but it truly did fix the problem here. I'm hoping that someone will save themself googling and spitballing 100 irrelevant solution attempts when, as stupid as it is, just rebooting fixes it.

VBA editor auto-deletes spaces at the ends of lines

Is there a way to convince the VBA editor in Excel to stop auto-formatting lines to remove the space at the end when I pause in my typing for a quarter second?
I had this exact problem and the following worked for me.
Click the Microsoft Office Button, and then click Excel Options
Click the Add-Ins category
In the Manage box, click COM Add-ins, and then click Go.
Look for an add in called 'Load Test Report AddIn' then uncheck it
restart excel
This addin is installed with VS2010 Beta2
In Excel 2010, toggling Design Mode button on the Developer Ribbon Tab solves the problem for me.
I've definitely had that issue before, where the vba editor would format as I was typing (not just when I went to another line). For me, it seemed to be related to a Microsoft Web Browser control that I had in an open workbook. When I took out the web browser, the VBA editor started acting normally again. I have no idea why that worked, but it did. Now I avoid using that control in my workbooks.
Something is causing your spreadsheet to recalculate while you are in the VBA Editor and this 'compiles' your code and thus strips the spaces. You need to stop the cells recalculating while you are editing. Turning the calculation to manual in the spreadsheet.
Tools > Options > Calculation should do the trick.
I noticed this when I had cells recalculating thanks to a DDE connection.
There is sort of a way to turn off the auto-"correction" in the VBA Editor.
Tools Menu -> Options -> Editor Tab -> Clear the Auto Syntax Check box
Sadly, this won't solve all your problems, as the VBA Editor tends to have a mind of its own, for better or worse.
Taking it out of design mode fixes it every-time on vba2003 - its was driving me crazy at first ... i did notice it might have something to do with the web control but when i take it out of design mode it works fine ... just toggle that to get it to behave :)
I have had this same problem several times recently, and has driven me crazy.
After reading this post all the different fix-ups mentioned (none worked for me), I recalled I have been playing lately with Internet Explorer Control, opening Internet Explorer from VBA.
This is mentioned in some of the answers in this post.
This got me in the right path and, in order to fix it, I had to first delete all iexplore.exe instances (alt+control+delete), closed Excel and open excel again.
(iexplore.exe had been opened invisible from the VBA code, and I didn't know they were running)
That fixed the bug.
I have been programming quite heavily with VBA for over 4 years, and never had this problem.
Just a couple of weeks ago I started using IE control, and I started getting this problem...so in my case I can only assume the bug is directly related to the IE control.
I am running both excel 2003 and 2007 in same PC at the same time, and the problem only happens with excel 2007.
None of the above for me.
I had a Application.OnTime timer that fired every second and this triggered a recalculation of something: commenting it made my day.
This has started happening to me recently after adding a Timer event to an Access 2007 form. The VB editor "finalizes" the current line (as if you had moved the cursor off of the statement; I have auto syntax checking off) each time the event fires (initially I had it set to 1 second, now it is set to 5 seconds, and the behavior scales accordingly). In order for the event code to execute, the application has to ensure that it has been compiled. Presumably, the editor needs to be in a "sane" state to do this, as it probably has to check for code dependencies among modules. Note that the behavior occurs regardless of whether any dependent code is actually loaded into the editor at the time. Note also that resetting the execution state doesn't affect the timer event firing. As a practical matter, one could close the triggering form, switch it to design view, set a breakpoint in the triggered code, or increase the timer interval while working with the editor.
In contrast to abhishek's comment, changing the settings of Tools/Options.../General/Compile On Demand and/or Background Compile did not affect the issue.
If it helps, none of the previous answers solved mine. Only solution appeared to be to close the xls file and reopen it. Frustrating to have to do every 30 mins but at least it works. Would love to know why it's recompiling and cleaning the text... should really be an option to disable the text cleanup but couldn't find it.
Turn off Tools > Options > General > Background Compile. This solved it for me.
This is a long standing problem that could have various causes. I had this same issue occur in the Access VBE (so naturally the Excel answers weren't relevant). After a LOT of digging I finally got it fixed with the solution below. First a recap though:
If you are here because of this issue in Excel, try the solutions above first. To summarize:
The most common issue in Excel is that the Design button is toggled. Toggle that and see if the behavior changes as submitted by Dmitry Frenkel above
If that doesn't work, check for the "Load Test Report" AddIn as mentioned by Ade.
Those are really the two main causes in Excel, but if neither of those solutions work, then scroll through the rest of the solutions here. All are valid possibilities for the cause. In Access the cause is pretty straight forward. It's a timer issue on a form somewhere. I found this solution from here by User Kevin K. Sullivan.
Copy the following line of code onto the clipboard. (You might need to
paste it into a text editor first and coerce it onto one line, depending on
your newsreader. It must be one line.)
For i = 0 to Forms.Count -1: Debug.Print Forms(i).Name, Forms(i).TimerInterval: Next i
Switch to Access.
Press Ctrl-G to go to the Immediate Window.
Press Ctrl-V to paste in the code.
Press enter to to run the code. All open forms will be listed. Any non-zero timer intervals are your culprits. Simply close that form (It may be invisibly open from another process than the one you thought you were dealing with).
I think the solution for Access here is what the user Dom was trying to say above. I guess the down votes were because it wasn't explained very well and/or because he was speaking of Access when the OG issue was in Excel. Regardless, he is likely on point if you are here because of the VBE in Access.
I hope this helps people. I know I kept finding this page when researching this issue, so that's why I thought I'd update this solution here.
I hit this problem today on a fresh install of Excel 2010 Beta 2. None of the above made any difference, but going into the trust center and disabling all application add-ins fixed the problem for me.
I have Office 2010 Pro and I had the same issue. As I type the space between each word was being deleted. After trying each of the options turning them on and off the only way I found working was to disable the Winzip Courie(excel) add-in. This is done thru the Options dialog box Add-Ins section.
In office 365 I had the same issue - what worked for me is I saved the file with a different name and when I re-opened the new file the problem went away.
I found this issue pops up when I had AutoSave on. Turning that off let me code without it compiling every second.
I don't think I've ever seen the VBE remove a space when I've stopped typing. It will remove trailling spaces from lines if you move to another line, but that's something different and not behaviour that I think can be altered.
The removal of spaces in the VBA editor for Access occurs when a form is open in Form("Execute") mode. This is probably due to background executions based on "On Timer" methods. Close the form in Access solves the problem in VBA.

Resources