As the title suggests, I am having a problem with Excel's Workbook_BeforeClose event handler. I know I am using the correct method signature (shown below) because it has worked in the past, and I have correctly placed the event handler in the "ThisWorkbook" module of the VBA editor. However, I have noticed that whenever I do a significant amount of coding within the VBE (in other modules), this method is not executed. Even when I place breakpoints inside, the breakpoints are not hit before the workbook closes. Again, this only happens if I have been messing around with other modules in the VBE; if I just open the workbook and immediately close it, this method runs fine and the breakpoints get hit. Saving or not saving the workbook does not seem to make a difference, and this problem occurs in Excel 2013 and 2016 (haven't tried opening the workbook in earlier versions). This issue is really starting to impede my workflow, so if anyone has a thought on why my Workbook_BeforeClose handler is not being called, I would very much appreciate the help!
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'More code...
End Sub
After posting this question on the Mr. Excel forum, I was given the solution: Some of the other modules that I was editing contained optimization code. This included disabling Application events while the macro was running, then turning them back on after completion. However, while debugging, I would obviously occasionally stop the macro before it completed, so Application events were never being turned back on!
So now, all I have to do is execute "Application.EnableEvents = True" in the Immediate Window before I try to close the workbook, and my event handler runs fine!
Related
I have Workbook_Open event, which fires a script with lots of code. It runs very long (getting data from web) and I would like Excel to open the file while it runs, this VBA also shows progress on status bar. I use loops and DoEvents has been used on each iteration with no effect. Only when macro executes successfully or I use Ctrl + Pause Break, file opens. Any ideas what can be wrong and how it could be fixed?
Edit: I didn't attach the code, as I am not the author and there are hundreds of lines in it. I had hope of finding a general cause why such situation would happen, from someone who encountered similar.
Important: it appears that the initial version of the file which I received from colleague works correctly until I save the file, so there isn't any "bug" in the code. Using VBADebugger didn't help. There are no external connections and names in the file.
I solved the problem by letting VBA excecute Workbook_Open event ASAP. I put the whole earlier content of Private Sub Workbook_Open under "scraper" procedure and now it looks like this:
Private Sub Workbook_Open
Application.OnTime Now + TimeValue("00:00:01"), "scraper"
End Sub
It must be that Excel won't (sometimes?) open the file before executing Workbook_Open event.
I can't get the name of the workbook when I use a add-in.
I'm trying to develop a add-in that runs each time you open Excel and reads the filename of the open file.
If the file name is XCFIL.SKV then do something...
This code should do it, but it doesn't. What am I missing?
The code stops and if I debug and press F8 it works fine, but it won't run on it's own.
Private Sub Workbook_Open()
If ThisWorkbook.Name = "XCFIL.SKV" Then
MsgBox "y"
End If
End Sub
Background:
Based in this statement The code stops and if I debug and press F8 it works fine, but it won't run on it's own. I assume the problem relies on the speed of the processor that is not sync with the code (own experience).
Solution:
Since it is Excel and the problem seems to rely only in the opening of the instance itself, you may use Application wait or any of the other functions for this matter.
Further thoughts:
Life cycle comes to my mind in these kind of scenarios. This web page has a neat Lifecycle diagram of excel instance (attached since I will try to explain the scenario)
As you may see "Application" is the first cycle of the Excel application, followed by "Open" and after that "Workbook" object, it may happen that in this life cycle "worbook" has not been created when "Open" comes to play,hence, you need to wait until excel solves this.
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.
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.
When I try to show userform1 with userform1.show in ThisWorkbook within the private sub workbook_open(), it does the strangest thing. (I'm using Excel 2007)- It enters break mode and stops the running of the code!!!
I open the macro enabled workbook and the userform appears as planned, but the when I move the mouse within the area of the userform it enters break mode and highlighting the row UserForm1.Show as if it is the problem.
Furthermore when I press F8 it's highlighting the private sub workbook_open() and another press highlights userform1.show again and another press shows me the run time error '400'.:
application-defined or object-defined error.
This has never happened to me before, I found a post that says it has no answer here.
Any ideas?
I also came across the same scenario.
What I did was to change the ShowModal property in the Form properties to False and the break went away.
I had the same problem, and the answers above didn't fix it. Restarting the PC resolved it temporarily, but after a while the problem returned. After a few frustrating days with a lot of restarting the pc, I came up with these conclusions:
What I think causes the problem is when you use ctrl+break to stop the code while running.
What solves the problem for me is to press ctrl+break while the code is NOT running, it'll show that it's in break-mode, and then press F5. It won't start running, but it will exit break mode again. When you've done this the problem should be fixed and you can run the code as usual.
I guess this method works the same as restarting your pc, but it's a lot faster.
It's an odd behaviour I already faced some times when dev'ing... some tips that might help you out:
Compile the code
Clear all breakpoints
Check project references (missing references may cause problems)
Add some unnecessary statement (like if 1 = 2 then DoEvents) before the 'hidden breakpoint', compile the code and then remove the code again
Install & run VBA Code Cleaner
Either way, that's a mystery for me the cause of this odd issue. It seems that somehow some breakpoints are kept in the memory even after removing them...
Hope it helps!
First thing to try is to recompile your VBA project and then save the workbook containing the macro. If compiling throws up an error you will probably get more information from the compiler message such as a missing reference.
Also make sure that you cleared all previously existing breakpoints. It might be the case that you first have to create a new breakpoint (F9) and then clear all breakpoints (Ctrl+Shift+F9) for the command to be enabled.