arrays - 在vba中随机播放数组

标签 arrays excel vba shuffle

我需要在没有重复的情况下对数组中的值进行洗牌,我需要在代码中添加什么以避免重复

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

enter image description here

关于arrays - 在vba中随机播放数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61020724/

相关文章:

Python:迭代数组的行和列

r - 使用R在Excel工作表中创建图表

python - 如何使用 Python 或 R 将 Excel 中带有替代文本的图形导出为 PDF?

sharepoint - 无法使用 Excel 中的 ADODB 连接到 SharePoint 网站

vba - 使用 vba 在 Excel 中对形状进行分组和命名

c++ - 将字符串转换为数组,strcpy 不起作用

javascript - 单个数组内的对象值之间的比较

java - 在java中解析嵌套的json数组

mysql - 变量在 IN 子句中不起作用

vba - ThisWorkbook 不工作