Who Dis
Who Dis

Reputation: 76

ListBox loop is skipping the first item when multiple items are selected

Like the title says, I have some code that loops through a list box and sets some variables to the selected item. As soon as the user selects more than one item, the loop skips over the first item selected. However, if only one item is selected, it works correctly. I cannot make sense of this!

With Me.lstQualifier
    For iCnt = 0 To Me.lstQualifier.ListCount - 1
        If (Me.lstYear.Selected(iCnt) = True) Then
            qual = Me.lstQualifier.Column(1)
            qualType = Me.lstQualifier.Column(0)
            Call AddQualifier(ProductCat, make, model, yr, BasePart, qual, qualType)
        End If
    Next
End With

Upvotes: 0

Views: 124

Answers (2)

June7
June7

Reputation: 21370

Instead of looping through all items, loop through selected items. Since you have With Me.lstQualifier don't need to repeat Me.lstQualifier in loop.

Dim varItem As Variant
With Me.lstQualifier
    For Each varItem In .ItemsSelected
        If Not IsNull(varItem) Then
            qual = .Column(1, varItem)
            qualType = .Column(0, varItem)
            Call AddQualifier(ProductCat, make, model, yr, BasePart, qual, qualType)
        End If
    Next
End With

Upvotes: 1

Who Dis
Who Dis

Reputation: 76

Silly mistake really. The .Column() function calls for the column number and row number. now the code looks like this

With Me.lstQualifier
    For iCnt = 0 To Me.lstQualifier.ListCount - 1
        If (Me.lstYear.Selected(iCnt) = True) Then
            qual = Me.lstQualifier.Column(1, iCnt) 'added iCnt as row number
            qualType = Me.lstQualifier.Column(0, iCnt) 'added iCnt as row number
            Call AddQualifier(ProductCat, make, model, yr, BasePart, qual, qualType)
        End If
    Next
End With

Upvotes: 0

Related Questions