Problem with Listboxes

  • Thread starter Thread starter djExcel
  • Start date Start date
D

djExcel

I have a strange problem which occurs every now and then.

I have created e.g. Form1 which has a ListBox1. Then I fill in the list with
years:

For X=2004 To 2010
Form1.ListBox1.AddItem X
If X=Year(Date) Then Form1.ListBox1.ListIndex=X-2004
Next X
Form1.Show

When user select OK button, I run a code which checks the selected year:

SelectedYear = Clng(Me.ListBox1)

Sometimes this gives me an error message if user doesn't change selection in
listbox. Although Excel shows that right year is selected it somehow is not.
If I use Form1.ListBox1.SetFocus command before I set the ListIndex property
then it works just fine. But why is it that sometimes it works and sometimes
it doesn't or am I doing something wrong here?
 
I don't know if it will cure the problem, but it might be more efficient if
you cut this:

For X=2004 To 2010
Form1.ListBox1.AddItem X
If X=Year(Date) Then Form1.ListBox1.ListIndex=X-2004
Next X

from the main module and put it in the Form1 initialize event. I believe it
would then automatically have focus when you show the form.
 
Back
Top