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

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

    If you construct a string containing the IDs already found through randomization, you can check for repeats.

    Dim i As Long, msg As String, id As String
    
    msg = Chr(9)
    For i = 1 To 20
        id = 1100 + Int((37 - 1 + 1) * Rnd + 1)
        Do Until Not CBool(InStr(1, msg, Chr(9) & id & Chr(9)))
            Debug.Print id & msg
            id = 1100 + Int((37 - 1 + 1) * Rnd + 1)
        Loop
        msg = msg & id & Chr(9)
    Next i
    msg = Mid(Left(msg, Len(msg) - 1), 2)
    
    MsgBox msg
    

提交回复
热议问题