【发布时间】:2019-07-29 07:26:01
【问题描述】:
在这个循环中,我检查之前使用的任何“随机”数字。但是有时它仍然会生成一个以前使用过的随机数?我不明白为什么,希望能以我的方式为错误提供指导。
'Generate Random Number and check against previous
Randomize
randomNumberInt = Int((9999 - 1000 + 1) * Rnd + 1000)
randomNumber = randomNumber & CStr(randomNumberInt) 'Convert the Int to a String
For Each Month In Months 'Search all sheets in a loop
With Sheets(Month).Range("I:I") 'Searches all of column I for the randomNumber to check if it has already been used.
Set Rng = .Find(What:=randomNumber, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
'MsgBox "Match Found so restart?!" 'Remove once finished
GoTo RandomNumberGenerator_Restart 'Value found so call the Sub again to try a different number
Else
'Value not found so carry on...
End If
End With
Next Month 'Next sheet/month
Exit Sub
在上一个问题中,我曾问过为什么假定的“随机”数字会连续重复...我没有使用 Randomize 来随机化种子数。我很欣赏现在重复的机会应该非常有限,但我仍然想了解循环如何不阻止重复值重新出现。
编辑:我应该注意到这个错误“似乎”是零星的,有时它运行良好,另一种情况下它抛出了一个以前使用过的“唯一”随机数......
【问题讨论】:
-
随机数生成...一个范围内的随机数。事实上,真正的随机数生成器的输出并不依赖于之前的输出。所以它可以生成2,例如,几次。如果您不想要以前的数字,则必须将生成器的输出存储在列表中,并检查新输出是否不在列表中。如果我们知道您计划实现的目标 - 为什么要搜索表格 - 我们可以建议更好的策略
-
我以为我已经预料到了,通过检查生成的 rand,如果它与之前的随机数相同,则重新运行循环。这就是我正在努力解决的问题,为什么我的条件没有抓住它。
-
使用生成器的输出,所以每个随机生成的都在工作表中。因此,为什么我在工作表中搜索以前使用过的工作表,如果匹配,循环应该重新运行,直到生成唯一的随机数。是的,可能肯定有更好的方法来做到这一点,但为了争论,为什么这不起作用?
-
什么是月份和月份?还有randomNumber的初始值?你做
randomNumber = randomNumber & CStr(randomNumberInt).为什么?为什么要改成字符串? -
我会尝试这些建议。谢谢。