室内设计培训
平面设计培训
部落窝教育
网站首页 >> Excel教程 >> 文章内容

三个vba生成不重复随机整数的案例

[日期:2012-03-05]   来源:IT部落窝  作者:IT部落窝   阅读:2188[字体: ]
内容提要:文章提供三个vba代码生成不重复随机数的案例供学习。

vba不重复随机数案例一:
下面的代码,将在A1:A5000单元格产生1-5000的不重复随机整数。
Private Sub vba不重复随机数()
    Dim Arr1(1 To 5000) As Boolean
    Dim Arr2(1 To 5000, 0) As Integer
    t = Timer
    [A:A] = Empty
    For i = 1 To 5000
        num = Int(5000 * Rnd + 1)
        Do While Arr1(num)
            num = Int(5000 * Rnd + 1)
        Loop
        Arr1(num) = True
        Arr2(i, 0) = num
    Next i
    [A1:A5000] = Arr2
End Sub


vba不重复随机数案例二:
在A1:A100中产生1-100的不重复随机整数,代码如下:
Sub vba不重复随机数()
  Dim TempArr1(99) As Integer, TempArr2(0 To 99, 1 To 1) As Integer
  Dim RndNumber As Integer, i As Integer
  Randomize (Timer)           '初始化随机数生成器
  For i = 0 To 99            '产生包含1-100的不重复的随机数列
      TempArr1(i) = i
  Next i
  For i = 99 To 0 Step -1
     RndNumber = Int(i * Rnd)
     TempArr2(99 - i, 1) = TempArr1(RndNumber) + 1
     TempArr1(RndNumber) = TempArr1(i)
  Next i
  '在A1:A100中输入这些数字
  Range("a1:a100").Value = TempArr2
End Sub


vba不重复随机数案例三:
在A1:A10单元格产生10个0-100的随机整数,以下是代码:
Sub vba不重复随机数()
   Dim i As Long
    i = 100
    Dim num As Long
    ReDim arr(i) As Long
    ReDim Arr2(i, 0) As Long
    Dim x As Long
    For x = 0 To i
        arr(x) = x
    Next x
    For x = 0 To i
        num = Int(Rnd() * (i - x))
        Arr2(x, 0) = arr(num)
        arr(num) = arr(i - x)
    Next x
    Range("A1:A10") = Arr2
End Sub

IT部落窝PS,CDR,213班 分享到: QQ空间 新浪微博 腾讯微博 人人网
photoshop教程
Photoshop教程
平面设计教程
Photoshop教程