Problem with Listboxes

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?
 
J

JLGWhiz

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.
 

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