listbox highlight selection

B

Bobby

Hi, after sorting information that I show in a listbox I would like to
highlight the first item showing up at top of the listbox(right now I
get by default a dotted line under the first item)
Thank's ahead for any hint!
My code:
Dim NoDupes As New Collection
Dim i As Integer, j As Integer
Dim Swap1, Swap2, Item
Sub slist()
i = 1
Set NoDupes = New Collection
For Each ws In Worksheets
NoDupes.Add (Worksheets(i).Name)
i = i + 1
Next ws

' Sort the collection
For i = 1 To NoDupes.Count - 1
For j = i + 1 To NoDupes.Count
If NoDupes(i) > NoDupes(j) Then
Swap1 = NoDupes(i)
Swap2 = NoDupes(j)
NoDupes.Add Swap1, before:=j
NoDupes.Add Swap2, before:=i
NoDupes.Remove i + 1
NoDupes.Remove j + 1
End If
Next j
Next i

' Add the sorted items to a ListBox
Userform1.ListBox1.Clear
For Each Item In NoDupes
Userform1.ListBox1.AddItem Item
Next Item

Userform1.Show
Set NoDupes = New Collection
End Sub
 
D

Dave Peterson

This worked ok for me. (And I put all the work into the userform_initialize
event:

Option Explicit
Sub userform_initialize()

Dim NoDupes As New Collection
Dim i As Integer, j As Integer
Dim Swap1, Swap2, Item
Dim ws As Worksheet

Set NoDupes = New Collection

For Each ws In Worksheets
NoDupes.Add ws.Name
Next ws

' Sort the collection
For i = 1 To NoDupes.Count - 1
For j = i + 1 To NoDupes.Count
If NoDupes(i) > NoDupes(j) Then
Swap1 = NoDupes(i)
Swap2 = NoDupes(j)
NoDupes.Add Swap1, before:=j
NoDupes.Add Swap2, before:=i
NoDupes.Remove i + 1
NoDupes.Remove j + 1
End If
Next j
Next i

' Add the sorted items to a ListBox
Me.ListBox1.Clear
For Each Item In NoDupes
Me.ListBox1.AddItem Item
Next Item

Me.ListBox1.ListIndex = 0

Set NoDupes = Nothing
End Sub
Private Sub CommandButton1_Click()
Unload Me
End Sub
 
B

Bobby

Thank's Dave! Tell me how would you call your Sub userform_initialize()
from a:
Private Sub Workbook_Open()
Thank's!
 
D

Dave Peterson

I would use the workbook_open event to show the form.

sub workbook_open()
userform1.show
end sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top