0

我正在尝试使用 Excel VBA 生成两个数字。介于 1 和 11 之间。如果数字相等,则第二个应该从随机重新生成。如果第一个是 8 或 9,那么第二个不应该是 8 或 9。如果是,它应该再次从随机生成。

这是我的代码:

Sub Foo()
    Dim thisNum As Integer
    Dim thatNum As Integer
        thatNum = Int((11 * Rnd) + 1)
        thisNum = Int((11 * Rnd) + 1)
        Do While thisNum = thatNum
            thatNum = Int((11 - 1 + 1) * Rnd + 1)
            break

        Loop
        Do While (thisNum = 8 Or 9) And (thatNum = 8 Or 9)
            thatNum = Int((11 - 1 + 1) * Rnd + 1)
            break

        Loop

        Range("F1").Value = thisNum
        Range("G1").Value = thatNum     
End Sub

它崩溃了,并且没有错误。我应该怎么办?

4

1 回答 1

3

您不需要中断循环,因为您处于带有条件的循环中。

您在这一行的情况是错误的:

Do While (thisNum = 8 Or 9) And (thatNum = 8 Or 9)

您无法与thisNum其他两个这样的数字进行比较。在您的情况下,您有一个无限循环。你是说 :

Do While (thisNum = 8 Or True) And (thatNum = 8 Or True)

所以是 :

Do While True

你可以使用这个循环:

Sub Foo()
    Dim thisNum As Integer
    Dim thatNum As Integer
    thisNum = Int((11 * Rnd) + 1)

    Do             
        thatNum = Int((11 - 1 + 1) * Rnd + 1)
    Loop While (thisNum = thatNum) Or ((thisNum = 8 Or thisNum = 9) And (thatNum = 8 Or thatNum = 9))

    Range("F1").Value = thisNum
    Range("G1").Value = thatNum     
End Sub
于 2013-05-16T06:19:35.520 回答