ListBox Item Selection

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

ListBox Item Selection

Post by jstevens »

Is there a better way other than recursing through a ListBox Index to find/highlight a specific item?

Code: Listbox.Value = Oranges
and Oranges would be highlighted as the selected item.

Example: Listbox contains
Apples
Bananas
Oranges
Pears
Strawberries

Your thoughts are appreciated.
Regards,
John

User avatar
HansV
Administrator
Posts: 78481
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: ListBox Item Selection

Post by HansV »

I must be missing something. Isn't the selected item in a list box highlighted automatically?
Best wishes,
Hans

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

Re: ListBox Item Selection

Post by jstevens »

Hans,

Here is an example file.

Code: Select all

Sub ListBoxItems()

UserForm1.ListBox1.RowSource = "'Sheet1'!A2:A6"

UserForm1.ListBox1.ListIndex = 2  'Item is oranges but it may not always be = 2

End Sub
EL_Listbox_Selection.xlsm
You do not have the required permissions to view the files attached to this post.
Regards,
John

User avatar
HansV
Administrator
Posts: 78481
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: ListBox Item Selection

Post by HansV »

And the question is? :scratch:
Best wishes,
Hans

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

Re: ListBox Item Selection

Post by jstevens »

Hans,

If the RowSource is modified to a dynamic range and Oranges' ListIndex changes from 2 to 5 then the code would have to be manually changed to UserForm1.ListBox1.ListIndex = 5.

The question is whether or not one can set the highlighted item to Oranges say with UserForm1.ListBox1.Value = "Oranges" or some other method.
Regards,
John

User avatar
HansV
Administrator
Posts: 78481
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: ListBox Item Selection

Post by HansV »

Yes, you can use

UserForm1.ListBox1 = "Oranges"

This will make "Oranges" the selected (highlighted) item, regardless of its position in the list box.
Best wishes,
Hans

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

Re: ListBox Item Selection

Post by jstevens »

Hans,

That was easy enough!
Regards,
John