Excel 2010/2013 intermittently pauses when saving workbooks via VBA - excel

I've had an intermittent problem for the last couple years and it's finally gotten to the point where I really need to try tracking down a solution.
I'm running a VBA script that takes various csv files that are spit out over the course of the day and chops them up for use in various other processes.
Every 20 minutes it opens a workbook with a 'Workbook_Open' block that does the work. When it finishes the job it closes the Excel application. It does this all day, every day.
MOST of the time this goes off without a hitch. OCCASIONALLY, it will hang up as it's trying to save a workbook. What I see when I catch it is the "Save as" box with the file path/name and the cancel button. It just waits there until someone clicks "Cancel" or the system fails from trying to open Excel too many times.
If I catch it and click the button then it will proceed on as if nothing abnormal had happened. Otherwise it just waits there for the user to click the button, as if it were any other msgbox/inputbox.
The weird thing is that the file is saved regardless of whether or not I click "Cancel" or kill the application or whatever. There doesn't seem to be any pattern to when it happens.
I've tried searching for similar issues but all my searches inevitably come up with results relating to system/application crashes. This isn't that. Excel will continue as normal, even to the point of continuing to save files in the way it SHOULD behave, if I click cancel.
Help?

I solved this problem by adding calls to DoEvents before and after the .SAVEAS or .SAVE calls. It's just two days, but this seems to have taken a process that I run daily multiple times a day (that creates multiple workbooks to a shared drive and never got through a day without this bug happening) to being a perfectly hands off process.

Related

Allow "Mouse Click" event or "switch Excel tab" when a macro is running

I have a macro that extracts data from Microfocus RUMBA Mainframe Display and puts in Excel rows one after the other. I have created a Global Mainframe object and that is used for extraction to Excel. But when the process is running and if user decides to stop the processing he cannot click on Stop button on Excel or go to different tabs to see the data being pasted. He has to clicks like 6 times before tabs are switched or stopped.
I see that DoEvents allows mouse click events in the loop to do things but the code is written in a way that there is a lot of lines with in the loop and a function with no loop, and placing DoEvents after everyline seems irrational. I have a feeling there is a better to do that but not sure what that is. Can anyone please help?.
VBA is single threaded. So you can't have one VBA action interrupt another. If you had a cancel button, for example, and the user was allowed to click it via a DoEvents processing the cancel action would still run after the currently running procedure.
In Excel this single threaded nature ends up being a good thing because you generally don't want the user interacting with the workbook while you are making programmatic changes. If this was allowed you would get undefined behavior.
Your best course of action would be to make a .NET application that uses the Excel Interop extensions to move the data from the mainframe to Excel. If you use VB.NET then you will find the code is quite similar to VBA. In fact, the Excel.Application object model is identical so the macro code you already have ports cleanly over.
There is an add-in that will help RUMBA development here:
https://www.microfocus.com/documentation/rumba/desktop951/RumbaSystemAdminGuide/GUID-DDB7571D-6167-4F8B-876E-E7450F3030B2.html

What causes this popup in Excel VBA?

I am making a simple tool for my job. It involves opening a file dialog box, selecting a file, opening it, analyzing it for different items, then creating a new workbook with the results. This is all done with VBA macros, activated via a command button.
The code works fine, all does what it's supposed to. However, at the start when the file dialog box is first opened, sometimes this error message pops up:
It doesn't affect the code or how it runs whatsoever, but it is a bit of a nuisance. There is no further detail provided for this "error". Does anyone know what might cause this popup?

Can't make Application.DisplayAlerts = False in Excel 2016 VBA

I have been chasing my tail for weeks, with more hours "Googling around than I want to admit.
I have a large, complex analytical app within an Excel 2016 spreadsheet that captures SQL table data, queries email data and does a lot of stuff that I think is pretty cool. Users see sales force automation performance metrics and charts. All is well except for one thing. I cannot stop the "save data?" dialog box from appearing no matter what I do.
As a workaround I've put the spreadsheet on on a network ride and given users a shortcut that runs a VBscript to copy this spreadsheet to a hidden drive on the local PC and runs it. So if they save it, there's no worries as they aren't working with the original data. But as one would easily imagine, the load time is necessarily longer than it need be and users are confused by a message when I am telling them they can't save the data.
Net of a lot of different experiments, it seems like I've uncovered a bug in Excel (yeah, I know, this sounds lame even to me) as I cannot make the Application.DisplayAlerts = False. It just will not take.
See image here:
enter image description here
The image above (or at the above link as I haven't submitted enough question yet to embed images) is obviously taken from the Immediate Window when I was running the app. I entered the steps in the exact order shown. Note that I set Application.DisplayAlerts = False and then checked the value immediately afterwords and it was True.
Very weird. Is this a bug?
One last aside that is probably irrelevant; I was using .XLSB format because of the smaller footprint, much shorter load time and to get around PC setup issues with macros. But I've switched back to .XLSX to simplify the experiment.
To clarify: the code temporarily halts after each single-step in the debugger, resulting in Excel setting it back to True while idle. Here’s a way to verify this behavior:
In the VBE code-development window, open the Immediate window (Ctrl-G).
Temporarily insert the following code somewhere in your routine:
Debug.Print "..."
Application.DisplayAlerts = False
Debug.Print "Application.DisplayAlerts: " & Application.DisplayAlerts
Stop
Using the “Set Next Statement” tool (or Ctrl-F9), set the Debug.Print "..." statement to be the next one to execute.
Run the code form there by pressing F5 (Continue).
You should see this displayed on the Immediate window:
...
Application.DisplayAlerts: False
Now, with the code stopped at the Stop statement, type “?Application.DisplayAlerts” in the Immediate window, and press the [Enter] key. You will get:
?Application.DisplayAlerts
True
because Excel has reset it to True while the code is suspended.
Remove the experimental code.

What happens when you close a workbook with code running?

I have a workbook on a network containing worksheet data and housing a generous amount of data, VBA code, forms etc. I developed a custom ribbon available via an add-in that opens this file and executes a macro when a button on the ribbon is clicked.
When the ribbon button is clicked, it executes a callback within the add-in that houses the custom ribbon XML file.
Code within the callback uses Application.Run() to open and execute the much larger network file that holds the worksheet data and macros needed for a lengthy automated process.
If a user cancels operation via the "Cancel" button on one of several forms (or if code successfully completes execution), via Application.Run it passes code execution back to another procedure in the add-in housing the custom ribbon.
This "EndProcedures()" macro in the add-in closes the network file.
The issue I am having is that code execution stops (as if an "End" command had been encountered) as soon as I close the network file which houses the vast majority of the VBA code. Since the user has the ability to cancel operation in the middle of the macro, the procedure call to the "EndProcedures()" macro in the ribbon workbook (the one that code execution began from) is something like #8 in the call stack, with #2-7 being procedures residing in the workbook that is being closed by #8. Since I want to halt code execution and the next line in the "EndProcedures()" macro is simply the global "End" command anyway, this isn't necessarily an issue. However, for the last couple of days I have been wrestling with some cryptic errors that I am thinking may be tied to the fact that I am closing a workbook while it has code running in the call stack. I have been getting "Out of Memory" errors in the VBA editor (though strangely I haven't seen them when the VBA editor is not open), and my thought is that this is due to either:
The code window for the network file simply being open in the VBA editor after the file itself is closed by other VBA code, OR
Perhaps actual memory issues due to object references not being cleared because the file was unloaded, rather than an "End Sub" or "End" line being encountered.
Though I use custom objects extensively in the macros housed in the network file, I am very careful about memory usage with them (which shouldn't even be that much) and don't think that this code is the source of the "Out of memory" errors. The question for now is whether or not closing a workbook with VBA code while code is running in the workbook being closed can cause "Out of memory" errors, and if so what can be done so that once macro execution ends users don't have my macro workbook open to wreak havoc with. Will I really have to code proper "Exit Sub" lines all the way out of the call stack?
This is my first post to StackOverflow, even though I probably learned 50% of what I can do in VBA from here, so please bear with me on this one.
After a few weeks of continuing to play with this, it doesn't appear that exiting code execution in the middle of a call stack involving multiple workbooks/modules was the source of the "Out of Memory" issues that were encountered. Though I haven't been able to pinpoint which edits actually addressed the "Out of Memory" errors, at least the issue has been resolved to my satisfaction.
P.S. - I answered my own question because it was no longer an issue, not because I necessarily pinpointed a resolution. As this was my first post to StackOverflow, if this was not the proper action to take please let me know.

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

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.

Resources