2016-01-09 54 views
0

我發現了一個選擇隨機單元格的函數,但它返回的也是重複的。隨機選擇沒有重複的單元格

Function RandomSelection(aRng As Range) 
    'Update20131113 
    Dim index As Integer 
    Randomize 
    index = Int(aRng.Count * Rnd + 1) 
    RandomSelection = aRng.Cells(index).Value 
End Function 

我需要的功能做類似但沒有重複。

+1

*'隨機選擇細胞沒有重複'*是一個矛盾。沒有什麼是隨機的,有附加條件。 – Jeeped

回答

0

我會用一個UDF()返回一個陣列

Public Function NoRepeats(inpt As Range) As Variant 
    Dim ary(), nItems As Long, i As Long 
    Dim r As Range 
    nItems = inpt.Count 
    ReDim ary(1 To nItems) 

    i = 1 
    For Each r In inpt 
     ary(i) = r.Value 
     i = i + 1 
    Next r 

    Call Shuffle(ary) 

    ReDim temp(1 To nItems, 1 To 1) 
    For i = 1 To nItems 
     temp(i, 1) = ary(i) 
    Next i 

    NoRepeats = temp 

End Function 


Sub Shuffle(InOut() As Variant) 
    Dim HowMany As Long, i As Long, J As Long 
    Dim tempF As Double, temp As Variant 

    Hi = UBound(InOut) 
    Low = LBound(InOut) 
    ReDim Helper(Low To Hi) As Double 
    Randomize 

    For i = Low To Hi 
     Helper(i) = Rnd 
    Next i 

    J = (Hi - Low + 1) \ 2 
    Do While J > 0 
     For i = Low To Hi - J 
      If Helper(i) > Helper(i + J) Then 
      tempF = Helper(i) 
      Helper(i) = Helper(i + J) 
      Helper(i + J) = tempF 
      temp = InOut(i) 
      InOut(i) = InOut(i + J) 
      InOut(i + J) = temp 
      End If 
     Next i 
     For i = Hi - J To Low Step -1 
      If Helper(i) > Helper(i + J) Then 
      tempF = Helper(i) 
      Helper(i) = Helper(i + J) 
      Helper(i + J) = tempF 
      temp = InOut(i) 
      InOut(i) = InOut(i + J) 
      InOut(i + J) = temp 
      End If 
     Next i 
     J = J \ 2 
    Loop 
End Sub 

這已被編碼,以回報格式,的結果(見的temp調光在UDF中)

enter image description here

注意,UDF()已在陣列的方式被輸入與按Ctrl ++輸入,而不僅僅是輸入鍵。

+0

我插入了函數,我得到#Name錯誤 – Emanuel

+0

@Emanuel確保所有代碼都在**標準模塊中** –

+0

它仍然返回重複項 – Emanuel

0

你可以在字典中的每個RandomSelection存儲

Does VBA have Dictionary Structure?

,然後設置RandomSelection查了字典之前(Dictionary.exists(值)),看看是否值您要設置爲具有之前使用過。