Link to home
Create AccountLog in
Avatar of Stephen LeCompte
Stephen LeCompteFlag for United States of America

asked on

How to highlight Access listbox with VBA function that passes listbox name and whether to highlight all or deselect?

Please note code and sample - for some reason its not allowing me to highlight all items when I click a button.  Appreciate any explanation along with the sample fixed.

https://filedb.experts-exchange.com/incoming/ee-stuff/8157-sample_highlight.mdb

Thanks,
Stephen

P.S.  I did try sListBox as ListBox and it didn't work.   I'd rather be shown how to do it both ways - with as a string and a listbox.
Private Sub Highlight_Items(sListBox As String, bShow As Boolean)

  Dim varItem As Variant
  Dim myItem As String
    For Each varItem In Me.Controls(sListBox).ItemsSelected
          'do whatever here in the loop
        
        Me.Controls(sListBox).Selected(varItem) = bShow
        DoEvents
        
    Next varItem
    
    Me.Refresh

End Sub

Private Sub cmdSelAllSource_Click()
  Call Highlight_Items("lstVolume", True)
End Sub

Private Sub cmdUnSelAllSource_Click()
  Call Highlight_Items("lstVolume", False)
End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of mbizup
mbizup
Flag of Kazakhstan image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Or using a ListBox parameter instead of a string name:

Private Sub Highlight_Items(lb As ListBox, bShow As Boolean)
    Dim I As Integer
    For I = 0 To lb.ListCount - 1
        lb.Selected(I) = bShow
    Next
End Sub

Private Sub cmdSelAllSource_Click()
  Call Highlight_Items(Me.lstVolume, True)
End Sub

Open in new window

Give those a try in your database, and post back if you have any trouble following/implementing either solution.
Sorry about the string of posts -

<<  Appreciate any explanation  >>

The reason your original code did not work is that you were looping through the 'selected items' collection.  To select or deselect all items, you need to loop through the entire list (the Selected Items collection is only a subset of this, which may include nothing at all).
Avatar of Stephen LeCompte

ASKER

Awesome - all postings helped!  When I do a search its harder to find the above gems.
:)

Glad to help out.