2017-09-14 242 views
1

我想创建一个基本上会根据用户输入返回随机数的宏,但是,我希望每个输出都是唯一的(这就是为什么randbetween()函数不起作用为了这)。以下是我到目前为止,但我不断收到参考错误。我已经从我在网上找到的几个不同的例子中拼接出了这些代码,所以我们也会以任何方式进行优化。创建生成唯一随机数的Excel VBA宏

代码:

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

试试这个

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 
+0

这看起来像它应该现在的工作。 – Jeeped

+0

@Jeeped - 错过了,谢谢指出,答案更新。 – Mrig

+0

您可能还想查看有关类型的其他答案:=错误。 –

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

你的Sample使用Type:=8这是一个Range然后你试图将它用作“偏移”功能中的“数字”。 更改此行:

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

要:

Sample = Application.InputBox("Enter the Sample Size", Type:=1) 
+0

谢谢kurtz!这工作! – Melk

+0

这并没有解决代码中'Selection'的抽象用法。 – Jeeped