2016-01-09 61 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(值)),看看是否值您要设置为具有之前使用过。