By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,213 Members | 1,307 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,213 IT Pros & Developers. It's quick & easy.

ListBox ListIndex behavior

P: 10
Hi All,

I am very new in the VBA coding and I've noticed this (to me strange) behavior:
Assume this code for "Value Items" type of single select two column ListBox:

If List98.ListIndex > -1 Then
List98.Selected(List98.ListIndex) = False
End If
List98.RowSource = ""
Set rst = CurrentDb.OpenRecordset( "any query" )
Do Until rst.EOF
List98.AddItem """" & rst![field1] & """" & ";" & """" & rst![field1] & """"

Let's say ListIndex was 2 before calling this code (third item is selected).
After point 1) ListIndex = -1 (no selection).

The "issue" is: When the third item is added in point 4) into the listbox the ListIndex property automatically sets itself back to 2 (the original value). Until the third item is added it remains -1. Adding next items doesn't change the ListIndex anymore so the final value is 2.

What am I doing wrong?
Thanks a lot.
Apr 22 '09 #1
Share this Question
Share on Google+
4 Replies

Expert 5K+
P: 8,679
ho this can hapen
I don't see how this can happen, but as a newly added last code line, try Requerying the List Box, namely:
Expand|Select|Wrap|Line Numbers
  1. Me![List98].Requery
Apr 22 '09 #2

P: 10
I believe using "Requery()" method on ListBox with RowSourceType = "Value list" doesn't have any effect.

Anyway, I finally got it working ...
The problem is that it is not possible to use "Selected()" method on single selection ListBox.
Although this line
Expand|Select|Wrap|Line Numbers
  1. List98.Selected(List98.ListIndex) = False
changes the ListIndex to -1 but the Value property remains set to the last selected item (it's bound).
This causes that when I put item with the same value as stored in the "Value" property the ListBox automatically sets its ListIndex to index of that value.

To avoid this beahavior it is necessary to unselect single selection ListBox using code:
Expand|Select|Wrap|Line Numbers
  1.  List98.Value = Null 
Apr 23 '09 #3

Expert 5K+
P: 8,679
Glad you figured it out.
Apr 23 '09 #4

Expert Mod 15k+
P: 31,707
Thanks for posting Juing. That area (with MultiSelects etc) can be quite complicated. The interface is far from intuitive.
Apr 23 '09 #5

Post your reply

Sign in to post your reply or Sign up for a free account.