Home » excel » Could not set the selected property of a multi-column ListBox in Excel VBA UserForm

Could not set the selected property of a multi-column ListBox in Excel VBA UserForm

Posted by: admin May 14, 2020 Leave a comment


I am unable to check an item in a multi-column user-form ListBox. The line lstPreConditionLogic.Selected(lstPreConditionLogic.ListCount) = True generates the following error:

Run-time error ‘380’: Could not set the Selected property. Invalid property value

I tried setting the value to -1 , checked but it did not work.

VBA Code

Private Function FillPreConditionLogicList()
    Dim varTemp             As Variant
    Dim intLoop             As Integer
    Dim strExpression       As String
    Dim PreConditionLogic   As clsPreConditionLogic

    With lstPreConditionLogic
        .ColumnCount = 3
        .ListStyle = fmListStyleOption
        .MultiSelect = fmMultiSelectMulti
        strExpression = TrimBlank(shtExpressionEditor.Range("rngExpText").Offset(, 1).Value)
        For intLoop = 0 To mDicPreConditionLogic.Count - 1
            Set PreConditionLogic = mDicPreConditionLogic.Items(intLoop)
            .List(intLoop, 0) = PreConditionLogic.Name
            .List(intLoop, 1) = PreConditionLogic.StartEnclosure
            .List(intLoop, 2) = PreConditionLogic.EndEnclosure
            varTemp = GetEnclosedString(strExpression, PreConditionLogic.StartEnclosure, PreConditionLogic.EndEnclosure)
            If varTemp <> "" Then
                lstPreConditionLogic.Selected(lstPreConditionLogic.ListCount) = True '//Gives Error
                strExpression = varTemp
            End If
    End With
End Function
How to&Answers:

You must subtract -1 from your .ListCount

lstPreConditionLogic.Selected(lstPreConditionLogic.ListCount - 1) = True

Because the list index stats counting at 0 but eg if the ListCount = 5 then the index of these 5 entries are 0, 1, 2, 3, 4 which means the last valid index is .ListCount - 1.