We help IT Professionals succeed at work.

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

stephenlecomptejr
on
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

Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2013
Commented:
To select/deselect all items:

Private Sub Highlight_Items(sListBox As String, bShow As Boolean)
    Dim I As Integer
    For I = 0 To Me.Controls(sListBox).ListCount - 1
        Me.Controls(sListBox).Selected(I) = bShow
    Next
End Sub

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2013

Commented:
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

CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2013

Commented:
Give those a try in your database, and post back if you have any trouble following/implementing either solution.
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2013

Commented:
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).

Author

Commented:
Awesome - all postings helped!  When I do a search its harder to find the above gems.
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2013

Commented:
:)

Glad to help out.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.