为什么生成的随机数不存储在变量中

时间:2013-01-21 02:43:19

标签: debugging excel-vba vba excel

这是我的代码

Sub lab1()

Dim first As Integer
Dim third As Integer
Dim total As Integer

total = 0

For i = 0 To i = 99
    first = Application.WorksheetFunction.RandBetween(1, 100)
    total = total + first
Next i

MsgBox (total)

End Sub

我正在尝试生成1到100之间的100个随机数,并将每个数字存储到变量“total”中。我不明白为什么总价值总是低于100,似乎'总'只存储1个随机数而不是100个随机数

2 个答案:

答案 0 :(得分:1)

对于i = 0至99 <&lt;这是一个需要注意的重要方面

Dim first As Integer
    Dim third As Integer

    Dim total As Integer


    total = 0

    For i = 0 To 99


    first = Application.WorksheetFunction.RandBetween(1, 100)



    total = total + first

    Next i

    MsgBox (total)

答案 1 :(得分:0)

VBA期待To之后的数字,因此行For i = 0 To i = 99被解释为For i = 0 To (i = 99),因为i刚刚创建了值{{1}表达式0等于i = 99,布尔值False转换为False

因此,行0被解释为For i = 0 To i = 99