VBA listbox_click event - itemsselected not registering

30 Views Asked by At

I have this code in the listbox's "on click" event. When the user selects an item in the listbox, the procedure runs but, the ctrl.ItemsSelected.Count = 0. For some reason, Access isn't registering that there is an item selected in the listbox so the For Each gets skipped.

Private Sub lstPositionID_Click()
    Dim PositionID As Integer, RS As Recordset, SQLstmt As String, ctrl As ListBox

    Set frm = Forms![Enter Candidate Duties]
    Set ctrl = frm!lstPositionID
    For Each varItm In ctrl.ItemsSelected 'get position ID
        PositionID = ctrl.Column(0, varItm)
    Next varItm
End Sub

How can I click an item in the listbox and then have this procedure run?

1

There are 1 best solutions below

0
Gustav On

Use the AfterUpdate event - as in this demo code:

Private Sub TestList_AfterUpdate()

    Dim Items()     As Variant
    
    Dim ItemsList   As String
    Dim Item        As Variant
    Dim Index       As Long
    Dim Count       As Long
    
    Count = Me!TestList.ItemsSelected.Count
    If Count > 0 Then
        ReDim Items(Count - 1)
        For Each Item In Me.TestList.ItemsSelected
            Items(Index) = Item
            Index = Index + 1
        Next
        ItemsList = Join(Items(), ";")
    End If
    
    ' Save list of selected items.
    Me!ItemsList.Value = ItemsList

End Sub