Excel VBA做function时,将值返回给单元格将无法正常工作

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

它崩溃,并没有任何错误。 我该怎么办?

你不需要打破循环,因为你在一个条件循环。

你的条件在这一行是错误的:

 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