'生成52个1到100的不重复随机数
Dim i, j As Long
Dim ran(1 To 52) As Long
Dim tNum As Long
Dim isExist As Boolean
Randomize
For i = 1 To 52
    isExist = False
    
    tNum = Int(100 * Rnd + 1)
    Debug.Print tNum
    For j = 1 To i
        If ran(j) = tNum Then
           isExist = True
           i = i - 1
           Exit For
        End If
    Next
    
    If isExist = False Then
       ran(i) = tNum
    End IfNextFor i = 1 To 52
    msg = msg & ran(i) & Space(1)
Next
MsgBox msg

解决方案 »

  1.   

    private y(51) as longsub gen()
    dim n as long,s as long,a as long,b as long
    for n=0 to 51
    y(51)=n+1
    nextfor n=1 to 80
    a=int(rnd*51):b=int(rnd*51)
    s=y(a):y(a)=y(b):y(b)=s
    nextend sub 
    这个算法速度快得多
      

  2.   

    :) nik的算法很不错的。
    小改一下。:)private y(51) as longsub gen()
    dim n as long,s as long,a as long,b as long
    for n=0 to 51
    'y(51)=n+1 <==这里
    y(n)=n+1
    nextfor n=1 to 80
    a=int(rnd*51):b=int(rnd*51)
    s=y(a):y(a)=y(b):y(b)=s
    nextend sub
      

  3.   

    手误,呵呵for n=1 to 80
    a=int(rnd*51):b=int(rnd*51)
    s=y(a):y(a)=y(b):y(b)=s
    next
    考虑改为
    for n=0 to 50
    a=int(rnd*51):s=y(n):y(n)=y(a):y(a)=s
    next
    这样会好一点?讨论讨论
      

  4.   

    不错不错。  :)
    向Nik学习,精益求精。
      

  5.   

    Private Sub Command1_Click()
    Dim x As New Collection, a(0 To 51) As String
    For i = 0 To 99
    x.Add i
    Next
    For i = 0 To 51
    Randomize
    num = Int(Rnd * x.Count + 1)
    a(i) = Str(x.Item(num))
    x.Remove num
    Next
    MsgBox Join(a(), ","), 64, "52 random number between 0 and 99"
    End Sub