excel - 如何随机选择多个单元格并在消息框中显示内容?

标签 excel vba

我在单元格 A1-A37 中有一个 ID 号 1101-1137 的列表。我想单击一个按钮以随机选择其中的 20 个,不重复,并将它们显示在消息框中。

我现在所拥有的似乎是从数字 1-37 中随机选择的,而不是单元格的实际内容,我不知道如何修复它。例如,如果我从单元格 A37 中删除数字 1137,数字 37 仍然会出现在消息框中;如果我将单元格 A5 中的数字 1105 替换为字母 E,则 E 不会出现在消息框中,但 5 可以。

但是,如果我将“Const nItemsTotal As Long = 37”更改为等于某个其他数字,比如 31,它只会输出 1-31 的数字。

这就是我所拥有的:

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 & idx(i)
            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

我确定这是一个愚蠢的错误,但我迷路了。非常感谢您的帮助。

最佳答案

如果您构建一个包含已通过随机化找到的 ID 的字符串,则可以检查是否有重复。

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

关于excel - 如何随机选择多个单元格并在消息框中显示内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593315/

相关文章:

vba - 计算所有工作表上不同范围内的总计

excel - 自定义订单排序

sorting - Excel VBA 排序

python - Pandas DataFrame.to_excel 错误的日期时间

sql - 在 VBA SQL WHERE 子句中使用变量时遇到问题

excel - 使用 VBA 将 Excel 数据从列复制到行

vba - 以编程方式将带有宏的按钮添加到 Excel 文件

Excel VBA : Filter and copy from top 5 rows/cells

javascript - 一键导出2份报告

excel - 导入数值列中包含无效字符的数据