2017-09-14 247 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