Excel VBA执行功能,将值返回到单元格将无法正常工作

时间:2013-05-16 04:22:43

标签: excel vba

我正在尝试使用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

崩溃,没有错误。我该怎么办?

1 个答案:

答案 0 :(得分: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