在此循环中,我检查之前使用的任何“随机”数字。但是有时它仍然会生成以前使用过的随机数?我无法理解为什么,并且非常感谢您对我的方法中的错误进行指导。
'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
来随机化种子数。我意识到现在重复的机会应该非常有限,但我仍然想了解循环如何不阻止重复值重新出现。
编辑:我应该注意到这个错误“似乎”是偶发的,有时它运行良好,有时它会抛出以前使用的“唯一”随机数......
最佳答案
我将您的代码视为不是整个函数(例如,GoTo 标签在顶部某处丢失)。将整个内容复制/粘贴到 Excel 中可能更容易诊断。但我确实看到了一件奇怪的事情。
randomNumber = randomNumber & CStr(randomNumberInt)
似乎将新的 4 位随机整数与 randomNumber
之前的值连接起来。您是否可能正在搜索错误的值?
关于Excel VBA 循环检查重复项不起作用...有时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57243917/