随机化基诺卡

时间:2018-04-27 20:33:13

标签: excel excel-vba vba

Sub GetRandomCell()
    Range("A1:J10").Select
    For Each Cell In Selection
        If Cell.Interior.Color = vbYellow Then
            Cell.Interior.Color = vbWhite
        End If
    Next

    Dim i       As Integer
    Dim RNG     As Range

    Set RNG = Range("A1:J10")

    Dim randomCell As Long

    i = 1        
    Do While i < 20
        randomCell = Int(Rnd * RNG.Cells.Count) + 1
        If RNG.Cells(randomCell).Interior.Color <> vbYellow Then
            RNG.Cells(randomCell).Interior.Color = vbYellow
            i = i + 1
        End If
    Loop
End Sub

这是用于创建随机基诺卡的代码。然而,我们最近几次玩过(我们大约有20个人),我们中的一些人发现我们正在玩同一张牌。我做错了什么?

2 个答案:

答案 0 :(得分:1)

您可以使用Randomize函数随机化Rnd函数的种子。在每次迭代中调用它以确保Rnd不使用相同的种子,并且不会给您带来随机结果:

Sub GetRandomCell()
    Range("A1:J10").Select
    For Each Cell In Selection
        If Cell.Interior.Color = vbYellow Then
            Cell.Interior.Color = vbWhite
        End If
    Next

    Dim i       As Integer
    Dim RNG     As Range

    Set RNG = Range("A1:J10")

    Dim randomCell As Long

    i = 1
    Do While i < 20
        Randomize
        randomCell = Int(Rnd * RNG.Cells.Count) + 1
        If RNG.Cells(randomCell).Interior.Color <> vbYellow Then
            RNG.Cells(randomCell).Interior.Color = vbYellow
            i = i + 1
        End If
    Loop
End Sub

答案 1 :(得分:0)

grid.arrange不会以字符串形式报告 - 它会以数字形式报告。 vbYellow是65535到Excel。

所以 - 你需要将你的If语句调整为:

RNG.Cells(randomCell).Interior.Color
编辑:正如评论中所指出的,术语vbYellow和数字65535之间没有功能差异。这个解决方案不能解决上面的问题,但是我要离开它,因为评论中的信息很有趣。 / p>