Link to home
Create AccountLog in
Avatar of Clive Beaton
Clive BeatonFlag for Australia

asked on

How do I find the currently selected row in a listbox without using For Each?

How do I find the currently selected row in a listbox without using For Each?


I have a form with 2 listboxes A and B.  Listbox A is multiselect Extended.  Listbox B is multiselect None.  I find selected items in Listbox A with For Each, but I cant use For Each on Listbox B because it is within the For Each loop on List box A.

Avatar of Noah
Noah
Flag of Singapore image

Hi!

I think simply, it should just be..

int selectedIndex = listBoxB.SelectedIndex;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Gustav Brock
Gustav Brock
Flag of Denmark image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Hi,

the current one is "Value" as Gustav already said.

I just want to ask why you think:
but I cant use For Each on Listbox B because it is within the For Each loop on List box A

Of course you can use nested For Each Loops.
    Dim c1 As Collection
    Dim c2 As Collection
    Dim a As Variant
    Dim b As Variant
    
    Set c1 = New Collection
    Set c2 = New Collection
    
    c1.Add "x"
    c1.Add "x1"
    c2.Add "y"
    c2.Add "y1"
    
    For Each a In c1
        For Each b In c2
            Debug.Print a, b
        Next
    Next

Open in new window


Cheers,

Christian
There is also the Selected property for single selections:

User generated image
And the ItemsSelected for multiple selections:

User generated image
But I'm with @Gustav, you don't need a loop for a single selection list box.
Hi ste5an,

The "Selected" property is only True/False (for each ListBox entry), not the value.
https://learn.microsoft.com/en-us/office/vba/api/access.listbox.selected

The "ItemsSelected" returns the row number(s) of the Listbox which are selected.
To get the value, it needs "ItemData":
https://learn.microsoft.com/en-us/office/vba/api/access.listbox.itemsselected

Cheers,

Christian
Avatar of Clive Beaton

ASKER

Christian.  Thanks for clearing that up.  I can't reproduce so I guess I misread the message.