随机选择没有重复的细胞

时间:2016-01-09 12:26:06

标签: excel vba

我找到了一个用于选择随机单元格的函数,但它也返回了重复项。

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

我需要这个功能做类似的但没有重复。

2 个答案:

答案 0 :(得分:0)

我会使用 UDF()返回数组

to.bool <- function(boolstr) as.logical(as.integer(unlist(strsplit(boolstr,"")))) 
sum(to.bool("101001") | to.bool("010001"))
#[1] 4

已对此进行编码,以 格式返回结果(请参阅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 的调暗)

enter image description here

请注意,UDF()已以数组方式输入,其中 Ctrl + Shift + 输入而不仅仅是 Enter key。

答案 1 :(得分:0)

您可以将每个RandomSelection存储在字典中

Does VBA have Dictionary Structure?

然后在设置RandomSelection之前检查字典(Dictionary.exists(value))以查看您之前要使用的值是否已用过。