Listbox Row Selection Code

After adding a row to a listbox I want to select the newly added row. Is there any difference between these two lines of code:

mylistbox.Selected(mylistbox.LastIndex) = True

or

mylistbox.ListIndex = mylistbox.LastIndex

Any benefit of using one over the other?

The first won’t fire a Change event
The second will

The first will add a row to a group of deleted rows if you have multi selection enabled
The second won’t

So the “benefit” really depends on what you expect & want to happen
If you expect the change event then the second is what you want
But, as noted, with a multiselect it will change the selection from whatever it was (maybe many rows) to just the new one

Thanks Norman, One more question related to how this works related to having sorted listbox columns. Let’s say I add row to a listbox that already has 10 items. Will LastIndex return 11 or where the row belongs in the listbox in relation to the “sort” listbox.

I am trying to add an item to the listbox then select the newly added item, but sorting complicates things… If sorting is applied what would be the best method to select the newly added item if it was say third item in the list when sorting was applied?

Ideas?

last index returns the row index where the row was inserted

it has nothing to do with sorted or not

if your list was
a
b
c

and you insert a row, “z”, at index 2 then
a
b
m
c

NOW if you sort the list then of course it will move
How you keep track of it is up to you