Deselect single select listbox
I have a listbox on a userform which on which at any point a maximum of 1 items may be selected. setting the listbox to MultiSelect = fmMultiSelectSingle
provides this but prevents the user from deselecting the selected list item.
To accomplish this, I added a MouseDown
event which fires when an item is clicked regardless of the current selection state as opposed to the Click
event which only fires when a new item is clicked.
My code (simplified below) lets a user select an entry. When the entry is clicked, it is selected. When attempting to deselect the same entry by clicking it, the MouseDown
is fired, the item is deselected, which fires the change event, which is cut short by the blnDisableEvents
set to True
and returns to the MouseDown
sub which then runs to the end. But after the End Sub
on the MouseDown
sub, the item which was just deselected, is reselected which again fires the Change
event.
How can I prevent the reselection of the just deselected item in the listbox?
Setup:
Userform with a single Listbox called ListBox1
Code:
Option Explicit
Dim blnDisableEvents As Boolean
Private Sub ListBox1_Change()
If blnDisableEvents Then Exit Sub
End Sub
Private Sub ListBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
If Not Me.ListBox1.ListIndex = -1 Then
blnDisableEvents = True
Me.ListBox1.Selected(Me.ListBox1.ListIndex) = False
blnDisableEvents = False
End If
End Sub
Private Sub userform_initialize()
Dim i As Integer
With Me
For i = 1 To 2
.ListBox1.AddItem i
Next
End With
End Sub
链接地址: http://www.djcxy.com/p/59904.html
下一篇: 取消选择单选列表框