Random selection from list

后端 未结 2 453
無奈伤痛
無奈伤痛 2021-01-01 06:16

I have a list of items in an Excel worksheet, A1-B115. At the moment I can enter 10 variables which retrieves the correct data from the list.

Code now:

C1=1

2条回答
  •  臣服心动
    2021-01-01 07:22

    I would use a collection to make sure you don't get any duplicates.

    Function cItemsToPick(NrOfItems As Long, NrToPick As Long) As Collection
        Dim cItemsTotal As New Collection
        Dim K As Long
        Dim I As Long
    
        Set cItemsToPick = New Collection
    
        If NrToPick > NrOfItems Then Exit Function
    
        For I = 1 To NrOfItems
            cItemsTotal.Add I
        Next I
    
        For I = 1 To NrToPick
            K = Int(cItemsTotal.Count * Rnd + 1)
            cItemsToPick.Add cItemsTotal(K)
            cItemsTotal.Remove (K)
        Next I
        Set cItemsTotal = Nothing
    End Function
    

    You can test this function with the following code:

    Sub test()
        Dim c As New Collection
        Dim I As Long
    
        Set c = cItemsToPick(240, 10)
        For I = 1 To c.Count
            Debug.Print c(I)
        Next I
    End Sub
    

提交回复
热议问题