Home » excel » excel – ListIndex of current value of combobox without selection

excel – ListIndex of current value of combobox without selection

Posted by: admin April 23, 2020 Leave a comment

Questions:

In VBA, the ListIndex property of a Combobox shows the index (starting at 0) of the item selected in the overall list (array) of values in the Combobox. It shows -1 if there is no selection made.

When I bring up a sheet in Excel with a Combobox and the last value in it, it comes up with a ListIndex of -1, instead of the actual ListIndex of the item.

What is the trick in VBA to quickly getting the ListIndex of the current non-selected value?

I know I could manually check the array myself (the .List property), but I’m hoping that VBA has some quicker way to do this.

How to&Answers:

From VBA Help on the ListIndex Property:

The ListIndex property contains an index of the selected row in a
list. Values of ListIndex range from –1 to one less than the total
number of rows in a list (that is, ListCount – 1). When no rows are
selected, ListIndex returns –1. When the user selects a row in a
ListBox or ComboBox, the system sets the ListIndex value.

So I assume you aren’t selecting anything, but trying to read the selected value. That might explain why ListIndex returns -1.

Answer:

This works for me to retrieve the index of the displayed item in the combo.

        Dim dst As Worksheet: Set dst = Worksheets("MyData")
        MsgBox (dst.OLEObjects("combobox1").Object.ListIndex)