我需要在没有重复的情况下对数组中的值进行洗牌,我需要在代码中添加什么以避免重复
Function Resample(data_vector)
n = UBound(data_vector)
ReDim shuffled_vector(n)
For i = 1 To n
shuffled_vector(i) = data_vector(WorksheetFunction.RandBetween(1, n))
Next i
End Function
最佳答案
这将使数组随机化:
Function Resample(data_vector() As Variant) As Variant()
Dim shuffled_vector() As Variant
shuffled_vector = data_vector
Dim i As Long
For i = UBound(shuffled_vector) To LBound(shuffled_vector) Step -1
Dim t As Variant
t = shuffled_vector(i)
Dim j As Long
j = Application.RandBetween(LBound(shuffled_vector), UBound(shuffled_vector))
shuffled_vector(i) = shuffled_vector(j)
shuffled_vector(j) = t
Next i
Resample = shuffled_vector
End Function
你可以这样调用:
Sub try()
Dim x() As Variant
x = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
x = Resample(x)
MsgBox Join(x, ",")
End Sub
关于arrays - 在vba中随机播放数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61020724/