Excel Crashes Intermittently When Clicking Macro Button in Rapid Succession - excel

When a VBA macro button (not AcitveX button) is clicked in rapid succession Excel "sometimes" crashes.
The VBA code makes heavy use of object modules, so I was thinking it was a garbage collection issue. I explicitly set the top level object to nothing before exiting the button click macro thinking it would force a garbage collection. That did not work.
It is super frustrating because it is intermittent. Maybe 1 out of 10 to 20 times.
The code shown is just the button click handler. There is about 10,000 lines of code called from this handler, which I did not show. The VBA code reads information from the sheet, does some calculations, updates an excel chart on the sheet, and writes some data back to the worksheet. I do the usual turning off events and screen updates.
I am just hoping someone else has come up against the rapid macro execution causing excel to crash. Again, the VBA code runs fine, it appears to be a higher level excel issue?
Public Sub Clicked_UpdateWall_C()
Dim Wall As New CWall_C
Dim ExecutionSuccess As Boolean
Dim errstr As String
ExecutionSuccess = CheckUnits(ActiveSheet.Name, errstr)
If ExecutionSuccess Then ExecutionSuccess = Wall.UpdateWall(ActiveSheet.Name, errstr)
Call CheckError(ExecutionSuccess, errstr)
' This is an attempt to force excel to do garbage collection
Set Wall = Nothing
End Sub
The error message is "Excel has stopped working" not a VBA runtime error. One can click the "restart excel" button in the error dialog, and excel restarts and generally most of the time one does not lose work.
Since it is intermittent, I cannot post the exact excel crash dialog box text.

When a VBA macro button (not AcitveX button) is clicked in rapid succession Excel "sometimes" crashes.
A shot in the dark. Try this. Put your code in lieu of '~~> Rest of your code. Now no matter how many times you click in succession, nothing will happen.
Option Explicit
Dim DoNotRunProc As Boolean
Public Sub Clicked_UpdateWall_C()
If DoNotRunProc = True Then Exit Sub
DoNotRunProc = True
On Error GoTo Whoa
'
'~~> Rest of your code
'
Whoa:
DoNotRunProc = False
End Sub
Note: If you have a separate error handler in your code then adjust the above code accordingly.

I was able to resolve the issue by doing two things:
Switched from a "Button Form Control" to an "Command Button ActiveX Control." My hunch was that the ActiveX control is more robust in terms of handling rapid clicks. Turned out to be true.
Added the DoEvents function to the end of the Command Button ActiveX Control event handler. This pretty much eliminated the issue 99.9% unless someone is just being ridiculous clicking the button. The hunch here is that it gave Excel time to handle any outstanding events that perhaps were not handled properly due to rapid button clicks.
Thanks to all of you who responded with positive comments and suggestions.

Related

Command Button doesn't work when first clicked

All the programming I have learnt is through manuals and websites such as this. So I wouldn't call myself a programmer but I do use a lot of quick and dirty macros to make my life easier. Occasionally, it all falls down and assistance is required!
I have a workbook that summarises the jobs I have worked on. In order to work quicker I have added a few command buttons too speed up simple tasks like filtering the blanks in a specific column. Normally this works OK. It is three weeks since I last used the workbook and today it is misbehaving. Click on a command button and the ribbon turns mostly grey. Click on the button again and the code runs and the ribbon returns to normal.
I have put a breakpoint in the code. On first click the breakpoint is not reached. On second click the breakpoint is reached!
Interestingly, if I click the command button the first time and then go into the vba editor and click on the break button the ribbon returns to normal again. So something is happening but it doesn't get as far as CommandButtonIssd_Click.
The command button code looks like this:
Private Sub CommandButtonIssd_Click()
FilterIt 9
End Sub
Most of the other command buttons just act on a different column number.
In the main module the code is:
Sub FilterIt(FieldNo As Integer)
'
' Filter Macro
'
FilterOff
ActiveSheet.Range("A4").AutoFilter
ActiveSheet.Range("A4").AutoFilter Field:=FieldNo, Criteria1:="="
End Sub
Sub FilterOff()
Dim a As Range, b As Range, iRow As Integer, iCol As Integer
If ActiveSheet.AutoFilterMode Then 'on, turn it off
Set a = Selection 'keep current location
iRow = a.Row
iCol = a.Column
Selection.AutoFilter
Range(Cells(iRow, iCol), Cells(iRow, iCol)).Select 'reset current location
End If
End Sub
All this does is filter column 9 to show only the blank cells.
I am thinking that it's a Windows10, Office365 issue as the code has been stable for a while and it was working OK last time I used it. In which case, it's just a case of waiting for MS to sort it's bugs out and issue an update (every Thursday, regular as clockwork!).
OR my code is suspect and needs tweaking to stop it messing with the system.
You thoughts would be appreciated.
I had this same problem today with an Excel 365 workbook: All CommandButtons would not fire on first click. They would fire on subsequent clicks, however.
today it is misbehaving. Click on a command button and the ribbon turns mostly grey. Click on the button again and the code runs and the ribbon returns to normal.
In my case, the bad behavior disappeared when I closed and reopened Excel and then reopened the workbook. After that, CommandButtons fired upon first click. I concur with #MikeK that it appears to be an Excel bug.
Finally!
Same problem, different workbook.
New laptop, Windows 11, Office 365 and I think I have a better definition of the problem as a little more information is now available.
If I open the spreadsheet on the laptop screen the macro and command buttons on the spreadsheet all work fine.
If set up the monitor screen as a duplicate of the laptop screen it all works OK.
If I set up the monitor screen as an extended display, then move the spreadsheet to the monitor screen and try again it fails as follows:
Open the macro sheet and it loads OK on the monitor screen but the form with the menu on it is displayed on the laptop screen!?
Exit the macro and it takes me to the macro spreadsheet and three command buttons as it should do.
Click on "Open Contact List" and the spreadsheet content is replaced by plain black (or the contents of the underlying window!). Click again without moving the mouse and the (now invisible) button works and loads the contact list.
close the contact list and the excel window continues to display incorrectly as above.
click inside the excel window and all is restored.
same applies to the other two buttons.
Shouldn't all this be handled by the windows system?
Previously I could deal with having to click a button twice to make it work. Now I have to click an invisible button!
If it is a Windows bug, how do I report it?

Excel freeze after ListBox_DblClick if the mouse cursor is moved outside the Listbox during the event

Context
I'm using the Listbox_DblClick event of on an Excel Userform (within a .xlam AddIn) to do a bunch of thing (which mainly update the Userform, but alost does some external logging...). Those actions can take up to a few seconds.
Problem
Excel winbdows are let almost frozen if the user move the mouse cursor outside the Listbox during the ListBox_DblClick event.
Consequences
I cannot click anywhere on the UserForm or ActiveSheet or the VBA window. Even the close button of Excel is unresponding. But nothing seems to be running (the last line of the event has already ran, nothing visible on the CPU...)
To be able to interact with Excel again, I need to either :
move temporarly the mouse cursor back over the ListBox
or change temporarly the current Windows application (like by doing Alt+Tab twice).
Excel is then globally fine. There isn't any other consequence and everything runs OK after this freeze.
What I already checked
It's not related to an EnableEvents or ScreenUpdating issue. Those are correctly managed by the macro. Even adding two lines to set them to True at the end of the event don't resolve the issue.
It's not that the macro is still running. Adding Debug.Print "Finished" at the end of the event show that "Finished" prints normally, while Excel is kept frozen.
Since I don't want the user to launch a new event while the current event is still running, I prevent that by locking/delocking the many ListBox (including the one realted to the event) using ListBox.Locked at the beginning/end of the event. But commenting these lines doesn't resolve the issue.
Minimal Reproductible Exampe
Add an Array on a UserForm
Add the following code
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
For n = 1 To 3000
Me.Caption = n
Next n
Me.ListBox1.List = Array("Apple")
End Sub
Private Sub UserForm_Initialize()
Me.ListBox1.List = Array("Apple", "Banana")
End Sub
Double click on "Banana" and moove the mouse cursor
Note
In this post form 2012 (Editing listbox items in Dblclick event freezes Excel unless mouse moves over listbox), the user seems to encounter a similar issue.

Unexpected results from a Worksheet.Activate event

I’m running excel 2010 on windows 7.
The following macro does what you would expect, ie (1) inserts a new worksheet, (2) adds a rectangle, and (3) activates cell A1.
Sub addSheetAndButton()
Dim buttonSheet As Worksheet
Set buttonSheet = ThisWorkbook.Sheets.Add
buttonSheet.Shapes.AddShape(msoShapeRectangle, 100, 100, 100, 50).Select
buttonSheet.Range("A1").Activate
End Sub
My problem is when I try to run it with a Worksheet.Activate event, for example:
Private Sub Worksheet_Activate()
Call addSheetAndButton
End Sub
This time (1) a new worksheet is not inserted, (2) the rectangle is added to the worksheet associated with the activate event, (3) cell A1 is not activated and (4) the rectangle remains activated.
What am I doing wrong? Any help would be greatly appreciated.
Thanks very much for trying this. I’m sorry it has taken me a while to get back, but I’ve been experimenting with this. I have discovered that when I exit and restart Excel, the addSheetAndButton macro works as expected under the Worksheet.Activate event. However, I have a different macro that uses another Worksheet.Activate event to update some charts. On what seemed to be a random basis, this would create a “run time error 6” - an overflow that resulted from trying to assign an out of bounds value to a variable.
I never got this error if I bypassed the Worksheet.Activate event/macro and ran the chart update macro by hand. After resetting VBA/Excel from the “run time error 6”, the addSheetAndButton macro behaved exactly as I described in my original post. The only way to cure it was to exit and restart Excel.
I think (hope) that I have traced the source of the run time error back to a line in my chart update macro where I had selected rather than activated a worksheet before reading data from it – though I am surprised at the result. It is worth pointing out that once Excel entered the “not as expected” state, the on-screen message from the following two lines was the name of the previous active sheet and not “Sheet1”.
Worksheets(“Sheet1”).Activate
Msgbox ActiveSheet.Name
Again, the only apparent way to cure this was to exit and restart Excel.
Thanks again for your help.

RTD.RefreshData crashes when invoked from modal form

I have created a very simple modal form with two buttons: one just closes the form, and the other calls Application.RTD.RefreshData. In Excel 2003 this all works just fine, but in Excel 2010 the Application.RTD.RefreshData crashes with
Run-time error '1004': Application-defined or object-defined error
If I create the form as modeless everything works fine in both Excel 2003 and Excel 2010.
For what it's worth, this is all the code behind the form:
Private Sub RefreshDataButton_Click()
Application.RTD.RefreshData
End Sub
Private Sub CloseButton_Click()
Call Unload(Me)
End Sub
And I invoke the form using this code in my sheet:
Private Sub CommandButton1_Click()
Dim form As UserForm1
Set form = New UserForm1
form.Show vbModal
End Sub
I've scoured Google and SO for any information on this to no avail. Is it a known issue with Excel 2010, or am I really not allowed to call Application.RTD.RefreshData from a modal form?
EDIT: I should add that as far as I can tell there are no RTD servers in my Excel session.
EDIT2: Further investigation: the error does not occur in Excel 2003 or 2007; it does occur in 2010 and 2013.
In a normal RTD server, you use the excel callback to call UpdateNotify(), and then Excel will decide when to call RefreshData() based on the throttle settings and how "busy" it currently is. The definition of "busy" normally includes things like formula recalculations, saving the sheet, and having a modal dialog open.
Excel protects itself from external components when it considers itself busy by throwing an exception. This makes sense, as they don't want their application becoming unstable or locking up because of a greedy addin or macro. Essentially all calls you put in your code which access any part of the Excel object model (including your call to RefreshData()) can throw an exception if Excel decides it is "busy". I suspect that in later versions of Excel they have tightened their definition of "busy", which is why you are seeing this disparity with the modal dialog.

Userform in Excel 2013 disappears while switching an active workbook behind

I have faced one problem in Excel 2013. In my project, I have a userform that contains a listbox which lists names of all opened excel books.
When a user clicks on a particular name in the list, the appropriate book is activated. So the userform is always on top and while the user is clicking on the names in the list, he can see all opened workbooks getting activated one by one behind the active userform.
This is the way it used to work in Excel 2010.
Now, after upgrade from 2010 to 2013, if a user clicks on a name in the list, selected workbook gets activated but the userform disappears.
What exactly has been broken in Excel 2013 and what is the way to bypass this problem?
Yes, the default behavior has changed. In Pre Excel 2013, The different workbooks are shown within one main Excel window if opened in the same instance. But in Excel 2013, they are shown in their own window. And because of this a modeless userform will only be visible on top of the workbook that was active when the userform was loaded.
And I don't think this has a fix yet. It is by design and may not be fixed.
#Siddharth, based on what you said, I think I have a solution. When you open a form, it will only show up on top of the ActiveWorkbook. As long as all the code is in the same code thread (not sure if terminology is right) , you're stuck with the same workbook; But if you use the Application.Run or Application.Ontime commands it seems to start it's own code thread, which is independent enough to work. Just Activate the workbook/sheet first, and then Unload the form and remote call the macro that showed the form in the first place.
Unfortunately, you need to use Unload instead of Hide, because of the aforementioned issue; which means you need to save any/all options selected.
Private Sub lstFiles_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
ThisWorkbook.Application.Workbooks(lstFiles.Text).Activate
Unload Me
Application.Run "USER_Macro1"
'Application.OnTime Now(), "USER_Macro1"
End Sub
 
Private Sub USER_Macro1(Optional Control) ' As IRibbonControl)
ModelessForm.Show vbModeless
End Sub
I tested it in Excel 2013 and so far it even seems to work regardless of the Screenupdating = false issue seen elsewhere.

Resources