Andrew0649
Jul 5 2006, 12:37 PM
I am having trouble setting the index in a list box. If I do it on a form by itself then
me.listbox.listindex = 0
will set the first item in the list box to selected. When i try it with some selection code beforehand ie: determine if an item is in the listbox, find its index then try and set it I get the error:
run time error 7777
You have used the Listindex property incorrectly.
JohnLVMVP
Jul 5 2006, 12:46 PM
Unless the list box has MultiSelect set to something other than None and the Bound Column matches, you can simply assign the value to the list box.
Andrew0649
Jul 5 2006, 12:56 PM
Thats what I expected. Here is the code. IT has some dims at the top etc. Multi select is none and bound column is 2 the source is a table with two fields, id and name.
'Load the list box from the users table
SQLstr = "SELECT tblUsers.fldUserID, tblUsers.fldUserName FROM tblUsers ORDER BY [fldUserName];"
Me.lstLoginNames.RowSourceType = "Table/Query"
Me.lstLoginNames.RowSource = "tblusers"
Me.lstLoginNames.ControlSource = SQLstr
Me.lstLoginNames.SetFocus
'See if the the Active Directory User is in the user table
s = Nz(DLookup("[fldUserName]", _
"tblusers", "[fldUserName] = '" & ActiveDirectoryUserName & "' "))
'If not then select the first in the list
'else get the index of the the Active Directory User
If s = "" Then
Me.lstLoginNames.ListIndex = 0
Else
intIdx = -1
For intI = 0 To Me.lstLoginNames.ListCount - 1
If Me.lstLoginNames.ItemData(intI) = s Then
intIdx = intI
Exit For
End If
Next intI
'intIdx contains either the index of the value or -1
If intIdx >= 0 Then
Me.lstLoginNames.ListIndex = intIdx fails here
Else
Me.lstLoginNames.ListIndex = 0
End If
End If
End Sub
JohnLVMVP
Jul 5 2006, 01:17 PM
Then change it to:
CODE
If intIdx >= 0 Then
Me.lstLoginNames.ListIndex = s
Else
Me.lstLoginNames.ListIndex = 0
End If
Andrew0649
Jul 5 2006, 01:27 PM
Thanks John,
s is a string and would produce a type mismatch. When debugging the code it shows that the index is -1 and that the variable about to be passed in is 0 then the error. I was wondering if this could be to do with the way it is loading the data. I am unfamiliar with VBA but I am not sure how it is holding the list data. IT must be some type of array behind the control and I can only think that I have given it a source that is not allowing me to respond to its index.
JohnLVMVP
Jul 5 2006, 05:14 PM
If the list box is bound to the second column, and that column is a string - as indicated by your loop test, then there should be no data type mismatch. If index is -1, then the value wasn't found in the list box row source.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please
click here.