EDIT: After more fiddling around I discovered that the problem may not have to do with the listbox at all. The named cell I used as Control Source has data validation with a drop-down list. I just tried selecting from one of those lists, and the same thing happens: the cell clears immediately. I’m trying to figure out why.
ORIGINAL:
I have a listbox on a userform. The ControlSource is connected to a named cell on a worksheet.
When I select an item from the list, it won’t stay selected. The selection, and the cell its linked to by ControlSource, are immediately deselected.
I did some testing in the listbox events. (In the entire project, none of the other events have code except for Userform_Initialize and btnClose_Click.)
Private Sub lsttxntype_Change()
Debug.Print "Change event triggered"
End Sub
Private Sub lsttxntype_Click()
Debug.Print "click event triggered"
End Sub
Private Sub lsttxntype_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
Debug.Print "BeforeUpdate triggered"
End Sub
Private Sub lsttxntype_AfterUpdate()
Debug.Print "AfterUpdate triggered"
End Sub
Most of the events trigger twice:
Change event triggered
click event triggered
BeforeUpdate triggered
AfterUpdate triggered
Change event triggered
BeforeUpdate triggered
AfterUpdate triggered
However, when I slow the code down with breakpoints or Stop commands, it changes. Here I put a breakpoint at the End Sub
of Change
, clicked the listbox, and let it continue after it stopped:
Change event triggered
click event triggered
Change event triggered
click event triggered
Here I put the breakpoint at the start of AfterUpdate
:
Change event triggered
click event triggered
BeforeUpdate triggered
AfterUpdate triggered
(I think the listbox selection is deselected in the AfterUpdate event.)
Since all I have to do is pause the execution to get a different result, I think there must be some kind of background timing issue.
If I leave ControlSource blank, then none of this happens. But it also means I need to use code to update the cell from the listbox and vice versa. (I’ll do that if I have to, but either way it would be good to resolve this question)
5