VBA阵列问题

时间:2016-07-06 12:55:56

标签: vba excel-vba excel

我试图从0-1生成一个随机变量5000次。然后,将它们放入范围,例如0-0.05,0.05-0.1 ....所以我可以计算每个范围的频率。

然而,似乎代码不起作用。有人可以帮忙吗?非常感谢!!!!

Option Explicit
Option Base 1

Sub MNA()

    Dim Iteration As Long, i As Long

    Iteration = 5000

    ReDim AI1(Iteration) As Double

For i = 1 To Iteration:    Cells(4, 3) = i

    AI1(i) = RandomNumber

 Next i

Call Hist1(Iteration, 20, 0, 1, AI1)

End Sub

Function RandomNumber()

Randomize

RandomNumber = Rnd()

End Function
Sub Hist1(n As Variant, M As Long, Start As Double, Right As Double, arr() As Double)

   Dim i As Long, j As Long, Find As Long
   Dim Length As Double
   ReDim breaks(M) As Single
   ReDim freq(M) As Single


For i = 1 To M
    freq(i) = 0
Next i
    Length = (Right - Start) / M

For i = 1 To M
    breaks(i) = Start + Length * (i)
Next i

For i = 1 To n

    If (arr(i) <= breaks(1)) Then freq(1) = freq(1) + 1
    If (arr(i) >= breaks(M - 1)) Then freq(M) = freq(M) + 1

    For j = 2 To -1

        If (arr(i) > breaks(j - 1) And arr(i) <= breaks(j)) Then freq(j) = freq(j) + 1

    Next j
Next i

For i = 1 To M
    Cells(3, i + 13) = breaks(i)
    Cells(4, i + 13) = freq(i)
Next i

End Sub

1 个答案:

答案 0 :(得分:1)

这应该有效。就像arcadeprecinct说你有一个错字。您还必须将Call Hist1(Iteration, 20, 0, 1, AI1)放入循环中。

希望你能从中吸取教训。

编辑跟随罗杰的评论吼叫

Option Explicit
Option Base 1

Sub MNA()

    Dim Iteration As Long, i As Long

    Iteration = 5000

    ReDim AI1(Iteration) As Double

For i = 1 To Iteration:    Cells(4, 3) = i

    AI1(i) = RandomNumber
    Call Hist1(Iteration, 20, 0, 1, AI1)

 Next i



End Sub

Function RandomNumber()

Randomize

RandomNumber = Rnd


End Function
Sub Hist1(n As Variant, M As Long, Start As Double, Right As Double, arr() As Double)

   Dim i As Long, j As Long, Find As Long
   Dim Length As Double
   ReDim breaks(M) As Single
   ReDim freq(M) As Single


For i = 1 To M
    freq(i) = 0
Next i
    Length = (Right - Start) / M

For i = 1 To M
    breaks(i) = Start + Length * (i)
Next i

For i = 1 To n

    If (arr(i) <= breaks(1)) Then freq(1) = freq(1) + 1
    If (arr(i) > breaks(M - 1)) Then freq(M) = freq(M) + 1

    For j = 2 To M - 1

        If (arr(i) > breaks(j - 1) And arr(i) <= breaks(j)) Then freq(j) = freq(j) + 1

    Next j
Next i

For i = 1 To M
    Cells(3, i + 13) = breaks(i)
    Cells(4, i + 13) = freq(i)
Next i

End Sub