创建生成唯一随机数的excel VBA宏

时间:2017-09-14 15:17:04

标签: excel vba excel-vba

我想创建一个基本上根据用户输入返回随机数的宏,但是,我希望每个输出都是唯一的(这就是randbetween()函数不能为此工作的原因) 。下面是我到目前为止,但我一直得到一个参考错误。我已经从我在网上找到的一些不同的例子中将这些代码拼接在一起,因此也可以通过任何方式进行优化。

代码:

Sub RandomSample()
Dim cell As Range
Dim rng As Range
Low = 1
High = Application.InputBox("Enter population total", Type:=1)
Sample = Application.InputBox("Enter the Sample Size", Type:=8)
Set rng = Application.Range(ActiveCell, ActiveCell.Offset(Sample, 0))
For Each cell In rng.Cells
    If WorksheetFunction.CountA(Selection) = (High - Low + 1) Then Exit For
    Do
        rndNumber = Int((High - Low + 1) * Rnd() + Low)
    Loop Until Selection.Cells.Find(rndNumber, LookIn:=xlValues, lookat:=xlWhole) Is Nothing
    cell.Value = rndNumber
Next
End Sub

错误窗口: Error image

3 个答案:

答案 0 :(得分:3)

试试这个

Sub RandomSample()
    Dim cell As Range
    Dim Sample As Range  'declare Sample as Range
    Low = 1
    High = Application.InputBox("Enter population total", Type:=1)
    Set Sample = Application.InputBox("Enter the Sample Size", Type:=8)
    For Each cell In Sample   'use sample in loop
        If WorksheetFunction.CountA(Sample) = (High - Low + 1) Then Exit For
        Do
            rndnumber = Int((High - Low + 1) * Rnd() + Low)
        Loop Until Sample.Cells.Find(rndnumber, LookIn:=xlValues, lookat:=xlWhole) Is Nothing
        cell.Value = rndnumber
    Next
End Sub

编辑:

Sub RandomSample()
    Dim cell As Range
    Dim rng As Range
    Dim High As Long, Sample As Long
    Low = 1
    High = Application.InputBox("Enter population total", Type:=1)
    Sample = Application.InputBox("Enter the Sample Size", Type:=1)
    Set rng = Application.Range(ActiveCell, ActiveCell.Offset(Sample, 0))
    For Each cell In rng.Cells
        If WorksheetFunction.CountA(rng) = (High - Low + 1) Then Exit For
        Do
            rndNumber = Int((High - Low + 1) * Rnd() + Low)
        Loop Until rng.Cells.Find(rndNumber, LookIn:=xlValues, lookat:=xlWhole) Is Nothing
        cell.Value = rndNumber
    Next
End Sub

答案 1 :(得分:3)

这是一个符合你想要的公式:

=IF(ROW(1:1)<=$B$1,INDEX(ROW(INDIRECT("1:" & $A$1)),AGGREGATE(15,6,ROW(INDIRECT("1:" &$A$1))/(COUNTIF($A$2:A2,ROW(INDIRECT("1:" & $A$1)))=0),RANDBETWEEN(1,$A$1-COUNT($A$2:A2)))),"")

其中A1是总体,B1是样本量

enter image description here

答案 2 :(得分:2)

您的Sample使用的Type:=8Range,然后您尝试将其用作“偏移”功能中的“数字”。 改变这一行:

Sample = Application.InputBox("Enter the Sample Size", Type:=8)

要:

Sample = Application.InputBox("Enter the Sample Size", Type:=1)
相关问题