Results 1 to 3 of 3

Thread: [RESOLVED] Random listbox checked item

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Dec 2005
    Posts
    230

    Resolved [RESOLVED] Random listbox checked item

    Hi guy,

    I just want to ask if anybody know how to get a random checked item from a listbox.

    view my listbox attachment file..

    Thanks
    Attached Images Attached Images  

  2. #2
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    19,541

    Re: Random listbox checked item

    You want to randomly select an item only if it is checked? If so, the following is one way....
    Code:
    Private Sub Command1_Click()
        If List1.SelCount Then
            Dim rndItems() As Long
            Dim X As Long, arrayPos As Long
            
            ReDim rndItems(0 To List1.SelCount - 1) ' store listindexes of selected items
            For X = 0 To List1.ListCount - 1
                If List1.Selected(X) Then   ' is item selected/checked?
                    rndItems(arrayPos) = X ' store its position
                    arrayPos = arrayPos + 1 ' increment for next position in array
                    If arrayPos = List1.SelCount Then Exit For ' abort loop if all checked items processed
                End If
            Next
            arrayPos = Int(Rnd * List1.SelCount) ' select a random list item from the array
            MsgBox List1.List(rndItems(arrayPos)) & " randomly selected and is checked"
        End If
    End Sub
    Note: If you expect hundreds of items, using APIs there is a much faster way to get all selected items. But if only a couple dozen items will exist, this should be fast enough.
    Last edited by LaVolpe; Nov 2nd, 2007 at 08:55 PM.

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Dec 2005
    Posts
    230

    Re: Random listbox checked item

    thanks alot

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width