I have a list box in a form. Clicking on it causes the form to jump to another record. It supposed to highlight an item and jump to the correct record. Instead, it highlights, and then instantly clears the selection, although it still jumps to the record. When I use standard record selection buttons, items are correctly highlighted.
I read the index of selected item from .ListIndex property because Selected() does not work in a Single Selection mode when I test which item is selected. However, .ListIndex is read-only property and I use .Selected() to highlight the item.
Option Compare Database
Option Explicit
Private Sub Form_Current()
Call highlightListBox
End Sub
Private Sub lbListBox_Click()
Dim rs As DAO.Recordset
Dim indx As Long
Set rs = Me.RecordsetClone
If Not rs.BOF And Not rs.EOF Then
rs.MoveFirst
rs.FindFirst "[ID]=" & CStr(Me.lbListBox.ItemData(Me.lbListBox.ListIndex))
If Not rs.NoMatch Then
Me.Bookmark = rs.Bookmark
End If
End If
rs.Close
Set rs = Nothing
End Sub
Private Sub highlightListBox()
Dim lngIndx As Long
Dim lngI As Long
Dim bNoMatch As Boolean
lngIndx = 0
bNoMatch = True
If Me.NewRecord <> 0 Or IsNull(Me!ID) Then
For lngI = 0 To Me.lbListBox.ListCount - 1
Me.lbListBox.Selected(lngI) = False
Next lngI
Else
Do
lngIndx = lngIndx + 1
If CLng(Me.lbListBox.ItemData(lngIndx - 1)) = Me!ID Then
bNoMatch = False
End If
Loop Until CLng(Me.lbListBox.ItemData(lngIndx - 1)) = Me!ID Or lngIndx = Me.lbListBox.ListCount
End If
If Not bNoMatch Then
Me.lbListBox.Selected(lngIndx - 1) = True
End If
End Sub