How can I randomly select a number of cells and display the contents in a message box?

前端 未结 4 1291
-上瘾入骨i
-上瘾入骨i 2021-01-22 13:11

I have a list of ID numbers 1101-1137 in cells A1-A37. I would like to click a button to randomly select 20 of these, with no repetitions, and display them in a message box.

4条回答
  •  深忆病人
    2021-01-22 13:23

    I've added a little to one line in your code... the line is now:

    strString = strString & vbCrLf & Cells(idx(i), 1).Value
    

    the full code is:

    Private Sub CommandButton1_Click()
    
    Const nItemsToPick As Long = 20
    Const nItemsTotal As Long = 37
    
    Dim rngList As Range
    Dim idx() As Long
    Dim varRandomItems() As Variant
    Dim i As Long
    Dim j As Long
    Dim booIndexIsUnique As Boolean
    
    Set rngList = Range("A1").Resize(nItemsTotal, 1)
    
    ReDim idx(1 To nItemsToPick)
    ReDim varRandomItems(1 To nItemsToPick)
    For i = 1 To nItemsToPick
        Do
            booIndexIsUnique = True ' Innocent until proven guilty
            idx(i) = Int(nItemsTotal * Rnd + 1)
            For j = 1 To i - 1
                If idx(i) = idx(j) Then
                    ' It's already there.
                    booIndexIsUnique = False
                    Exit For
                End If
            Next j
            If booIndexIsUnique = True Then
            strString = strString & vbCrLf & Cells(idx(i), 1).Value
                Exit Do
            End If
        Loop
        varRandomItems(i) = rngList.Cells(idx(i), 1)
    
      Next i
        Msg = strString
        MsgBox Msg
    ' varRandomItems now contains nItemsToPick unique random
    ' items from range rngList.
    
    End Sub
    

    So rather than returning the number, it uses the number returned to look at the value on the row that it relates to.

提交回复
热议问题