PDA

View Full Version : Select then Deselect Listbox item



gmaxey
05-24-2013, 09:07 AM
Somewhere in my vast collection of unorganized notes, I have a snippet of code that would let me unselect a single select listbox item by simply clicking on the selected item. I can't find it so after searching around the internet an coming up blank I wrote some code. Then as typical, I look around again and found something right off.

I'm posting both versions here. With a simple UF with two single select listboxes, call the form and then select an item and click again to deselect.

Anybody see any problems with either method, feel one is better than the other, or feel neither is worth posting and have a better suggestion? Thanks.
Option Explicit
Dim m_Deselect As Boolean
Dim m_Selection As Long
Private Sub UserForm_Initialize()
m_Deselect = False
With ListBox1
.AddItem"A"
.AddItem"B"
.AddItem"C"
End With
ListBox2.List =ListBox1.List
lbl_Exit:
Exit Sub
End Sub

Private Sub ListBox1_MouseUp(ByVal Button As Integer, ByValShift As Integer, ByVal X As Single, ByVal Y As Single)
If m_Deselect Then
IfListBox1.Selected(ListBox1.ListIndex) = True Then
ListBox1.Selected(ListBox1.ListIndex) = False
Else
ListBox1.Selected(ListBox1.ListIndex) = True
End If
End If
m_Deselect = Notm_Deselect
lbl_Exit:
Exit Sub
End Sub

Private Sub ListBox2_Click()
m_Selection = -1
lbl_Exit:
Exit Sub
End Sub

Private Sub ListBox2_MouseUp(ByVal Button As Integer, ByValShift As Integer, ByVal X As Single, ByVal Y As Single)
If m_Selection =ListBox2.ListIndex Then
ListBox2.Selected(ListBox2.ListIndex) = False
Else
m_Selection =ListBox2.ListIndex
End If
lbl_Exit:
Exit Sub
End Sub

Doug Robbins
05-26-2013, 12:03 AM
Hi Greg,

See the article "De-selecting a SelectedItem in a Single-Select Listbox” at:

http://www.word.mvps.org/FAQs/Userforms/DeselectListBoxItem.htm (http://www.word.mvps.org/FAQs/Userforms/DeselectListBoxItem.htm)

gmaxey
05-26-2013, 04:50 AM
Hi Doug,

Thanks. Being that at one point or another I've read every WordMVP FAQ that must have been the source of my missing notes. Seems that any one of the three (it and the two posted here) would work equally as well. Unless I am missing something.