随机数不是随机数并重复

时间:2019-07-28 05:35:06

标签: excel vba

这部分VBA代码按顺序产生相同的数字,我哪里出错了? 似乎重复一遍

   Months = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", 
  "Oct", "Nov", "Dec")
  randomNumber = vbNullString 'Clear any possible values that might be lurking

  On Error GoTo ErrorCatch: 'Just incase something goes horribly wrong

  RandomNumberGenerator_Restart: 'If random number happens to be a repeat, 
  restart from here.

   randomNumber = vbNullString 'Clear any possible values that might be lurking

  'Generate Random Number and check against previous
   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 developing
             GoTo RandomNumberGenerator_Restart 'Value found so call the Sub again to try a different number
        Else

            'Value not found so carry on and pass the value back...
        End If

    End With

    Next Month 'Next sheet/month

Exit Sub

我对VBA不太熟悉,请原谅。

0 个答案:

没有答案