如何使用随机数创建数组?

时间:2015-11-04 23:47:39

标签: arrays vba excel-vba random excel

我是新来的。我想创建一个包含16个元素的数组。让我们说我的数组是ReDim arr(15)作为整数,在那个数组中我想把数字从1到16但是加扰,例如arr(0)= 3,arr(5)= 8并且等等。

2 个答案:

答案 0 :(得分:2)

尝试一下:

Sub MAIN()
   Dim ary(1 To 16) As Variant
   Dim i As Long, msg As String

   For i = 1 To 16
      ary(i) = i
   Next i

   Call Shuffle(ary)

   msg = ""
   For i = 1 To 16
      msg = msg & vbCrLf & ary(i)
   Next i
   MsgBox msg
End Sub

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

答案 1 :(得分:1)

这是一些非常懒惰的代码:

Dim arr(15) As Integer
Dim i As Integer, j As Integer
i = 1
Do
    j = Int(16 * Rnd)
    If arr(j) = 0 Then
        arr(j) = i
        i = i + 1
    End If
Loop Until i = 17

Rnd从0到1生成single,将其乘以16并用Int去掉小数部分,它将为您提供0到15之间的随机数。

效率不高,我不会在制作中使用它,但它会完成这项工作。

希望这有帮助!