PDA

View Full Version : How to allow the arrows buttons on a listbox to change the selection?



Zuccj
06-29-2017, 07:54 AM
I have a listbox that is linked to a cell. Right now when I use the arrow keys on the keyboard the value in the cell changes. When I use the scroll bar up and down buttons it just moves the items in the list, but doesn't update the cell. Maybe a listbox isn't the best way to go about it? I thought about adding a spin button to the listbox as well, but since you can't hide the vertical scroll bar that doesn't really work. I tried doing:


With Sheet2.ListBox1
.AddItem "0"
.
.
.
If .ListIndex > -1 Then .Selected(.ListIndex) = True
End With

but that doesn't change anything, as the buttons aren't changing the selection. There has to be an easy way to allow the up and down arrows on the box to control the selection right?

mdmackillop
06-29-2017, 09:01 AM
This uses MouseMove over the listbox area

Private Sub ListBox1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
Dim i As Long
i = ListBox1.Height / ListBox1.ListCount
If Y \ i <= ListBox1.ListCount - 1 Then
Cells(1, 5) = Me.ListBox1.List(Y \ i)
Me.ListBox1.Selected(Y \ i) = True
End If
End Sub

Tom Jones
06-29-2017, 11:10 AM
Hi, mdmackillop

There is something curious about this UserForm in your file. When selecting data in the ListBox. Although the mouse indicates (say above) say Data 10, Date 12 is selected, ie 2 levels below the mouse.
Is it only me?

mdmackillop
06-29-2017, 11:36 AM
The selection highlight comes from the MouseMove, not the left click. If this suits the OP, i guess the left click selection should be disabled.

Tom Jones
06-29-2017, 02:22 PM
The selection highlight comes from the MouseMove, not the left click. If this suits the OP, i guess the left click selection should be disabled.

It's not necessary to click. If mouse indicate Data 13 it's highlight 2 levels below (data 15)
but if you indicate first or last data in ListBox then that data is highlight correct.

mdmackillop
06-29-2017, 03:07 PM
The methodology of the function requires movement over the listbox to be pro rata to the height and number of items. If all items are visible, this issue would disappear. Initially I used i = 5 but this meant that with 50 items, you can't access the higher values.