我有一个随机生成不同生产率的小程序。起初,我在没有数组的情况下编写了程序,在每一行都打印了值,这很有效,而且速度很慢。所以现在我尝试对数组做同样的事情,我的问题是打印值:
我的代码(如果你想测试运行它,应该可以将代码复制到 vba 并在 excel 工作表中有一个名为“Prodthishour”的单元格):
Sub Production2()
Totalproduction = 10000
Maxprodperhour = 150
Minimumatprod = 50
Timeperiod = 90
Nonprodhours = 10 'Isnt used yet
Openhours = 80
Producedstart = 0 'What we have at the start of the production, often nothing
Prodleft = 10000 'The total production is what is left in the beginning
Dim Produced
Produced = Producedstart
ReDim ProductionArray(Openhours, 1) As Double
For n = 1 To Openhours - 1 'Takes minus 1 value, as the rest will be the last value
A = Prodleft - Maxprodperhour * (Openhours - n) ' A secures that the randomness isnt such that the production wont be fullfilled
If A < 0 Then
A = 0
End If
If Prodleft > Maxprodperhour Then
Maxlimit = Maxprodperhour
Else
Maxlimit = Prodleft
End If
ProductionArray(n, 1) = A + Minimumatprod + Rnd() * (Maxlimit - Minimumatprod - A)
Cells.Find("Prodthishour").Offset(n, 1).Value2 = ProductionArray(n, 1)
Produced = Producedstart 'Sets it at the startvalue again to make sure it doesn't accumulate the values
For Each Item In ProductionArray
Produced = Produced + Item
Next
Prodleft = Totalproduction - Produced
If Prodleft < 0 Then
Prodleft = 0
End If
If Prodleft < Maxprodperhour Then
Exit For
End If
Next n
Cells.Find("Prodthishour").Offset(1, 0).Resize(UBound(ProductionArray, 1), 1).Value = ProductionArray
End Sub
最初的问题是打印值,但现在看起来数组“ProductionArray”只是打印为零。
我觉得这很奇怪,因为我使用
Cells.Find("Prodthishour").Offset(n, 1).Value2 = ProductionArray(n, 1)
测试打印列旁边的值,我真的希望将其全部打印并使用
For Each Item In ProductionArray
Produced = Produced + Item
Next
总结一切,都给我价值,但 ProductionArray 仍然打印为零
(已编辑)