Select all or clear all in a list box

R

Roger Carlson

Assuming you want the code behind a button, the following code will work.
Note: this button should have a default caption of "Select All". It will
then work as both a Select and UnSelect button.

'-------------------------
Private Sub cmdSelectAll_Click()
On Error GoTo Err_cmdSelectAll_Click
Dim i As Integer

If cmdSelectAll.Caption = "Select All" Then
For i = 0 To lstAnswerCat.ListCount - 1
lstAnswerCat.Selected(i) = True
Next i
cmdSelectAll.Caption = "Unselect All"
Else
For i = 0 To lstAnswerCat.ListCount - 1
lstAnswerCat.Selected(i) = False
Next i
cmdSelectAll.Caption = "Select All"
End If

Exit_cmdSelectAll_Click:
Exit Sub

Err_cmdSelectAll_Click:
MsgBox Err.Description
Resume Exit_cmdSelectAll_Click

End Sub
'-------------------------

The button is called "cmdSelectAll" and in the code above, the listbox is
named "lstAnswerCat". You will of course want to substitute your own
names. If you want to see a working version, on my website
(www.rogersaccesslibrary.com), is a small Access database sample called
"MultiSelect.mdb" which illustrates this.

--
--Roger Carlson
MS Access MVP
Access Database Samples: www.rogersaccesslibrary.com
Want answers to your Access questions in your Email?
Free subscription:
http://peach.ease.lsoft.com/scripts/wa.exe?SUBED1=ACCESS-L
 
J

JimS

Thanks Roger. Looks like a quick way to deselect all is to requery the
control as well. Takes less code, but probably orders of magnitude more
resources....

Thanks again.
 
D

Dale Fye

Jim,

This code does both for you. If you click when the button says "Select
All", it highlights all of the items, then changes the caption of the command
button to "Unselect All". If you click while it says Unselect All, it
deselects all of the items.

You could shorten it a bit by replacing the If Then statement with:

dim ItemValue as boolean
ItemValue = IIF(cmdSelectAll.Caption = "Select All", True, False)
For i = 0 To lstAnswerCat.ListCount - 1
lstAnswerCat.Selected(i) = ItemValue
Next i
cmdSelectAll.Caption = IIF(cmdSelectAll.Caption = "Select All", _
"Unselect All", "Select All"

HTH
Dale
--
Don''t forget to rate the post if it was helpful!

email address is invalid
Please reply to newsgroup only.
 
Top