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

前端 未结 4 1248
-上瘾入骨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:18

    Just shuffle the indices:

    Sub MAIN()
       Dim ary(1 To 37) As Variant
       Dim i As Long, j As Long
    
       For i = 1 To 37
          ary(i) = i
       Next i
    
       Call Shuffle(ary)
    
       msg = ""
       For i = 1 To 20
          j = ary(i)
          msg = msg & vbCrLf & Cells(j, 1).Value
       Next i
       MsgBox msg
    End Sub
    
    
    
    Public Sub Shuffle(InOut() As Variant)
        Dim i As Long, j As Long
        Dim tempF As Double, Temp As Variant
    
        Hi = UBound(InOut)
        Low = LBound(InOut)
        ReDim Helper(Low To Hi) As Double
        Randomize
    
        For i = Low To Hi
            Helper(i) = Rnd
        Next i
    
    
        j = (Hi - Low + 1) \ 2
        Do While j > 0
            For i = Low To Hi - j
              If Helper(i) > Helper(i + j) Then
                tempF = Helper(i)
                Helper(i) = Helper(i + j)
                Helper(i + j) = tempF
                Temp = InOut(i)
                InOut(i) = InOut(i + j)
                InOut(i + j) = Temp
              End If
            Next i
            For i = Hi - j To Low Step -1
              If Helper(i) > Helper(i + j) Then
                tempF = Helper(i)
                Helper(i) = Helper(i + j)
                Helper(i + j) = tempF
                Temp = InOut(i)
                InOut(i) = InOut(i + j)
                InOut(i + j) = Temp
              End If
            Next i
            j = j \ 2
        Loop
    End Sub
    

提交回复
热议问题