randomize a listbox

  1. 7 years ago

    Hi All.

    I am trying to modify a program I wrote for a person, whereby the require that the same person's name not appear one after another in a listbox.

    I think I need to use an array for this, but am not sure what my next step would be.

    Any pointers?


  2. Alwyn B

    21 Jun 2013 Johannesburg, South Africa
    Edited 7 years ago

    Hey Michael.

    Do I understand you correctly that all the names are already in the listbox and you want to randomize them?

    If so you can perhaps use a method similar to this one (add it to a module and make sure it's scope is global:

    Sub Shuffle(Extends lbox As Listbox)
      Dim i As Integer
      Dim swopIndex As Integer
      Dim rnd As New Random
      Dim tmpStr As String
      i = 0
      while i < lbox.ListCount
        swopIndex = rnd.InRange(0, lbox.ListIndex - 1)
        tmpStr = lbox.List(swopIndex)
        lbox.List(swopIndex) = lbox.List(i)
        lbox.List(i) = tmpStr
        i = i + 1
    End Sub

    You can now randomize the content of any listbox in your project, simply by calling:

  3. Hi there.

    That is actually EXACTLY what I was looking for.

    I was using a second variable, comparing the two to ensure they were not the same, and then writing into another array I created.

    Your way is INFINITELY more ... beautiful(???)


  4. 2 weeks ago

    Lennox J

    May 17 Jamaica. West Indies

    Thanks Alwyn,
    Great stuff.

  5. Rod P

    May 17 Testers

    Isn’t there a chance that the same name could appear next to each other though? By random chance?

or Sign Up to reply!