ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Problem with Listboxes (https://www.excelbanter.com/excel-programming/409450-problem-listboxes.html)

djExcel

Problem with Listboxes
 
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?

JLGWhiz

Problem with Listboxes
 
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.


"djExcel" wrote:

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?



All times are GMT +1. The time now is 12:30 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com