我有一个小程序,可以随机生成不同的生产速率。一开始我没有使用数组,每行都打印出值,这个方法虽然可行但很慢。现在我尝试使用数组来做同样的事情,但我的问题是如何打印这些值:
以下是我的代码(如果你想测试运行它,只需将代码复制到vba中,并在excel工作表中用名称“Prodthishour”创建一个单元格):
总结一下,两个变量都给了我值,但是ProductionArray仍然只打印出了0。
(已编辑)
以下是我的代码(如果你想测试运行它,只需将代码复制到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仍然只打印出了0。
(已编辑)
ProductionArray(n, 1) = A + Minimumatprod + Rnd() * (Maxlimit - Minimumatprod - A)
我觉得有点奇怪,因为对ProductionArray求和显然会得到应该得到的值。 - user2703642ReDim ProductionArray(Openhours, 1) As Double
,它与ReDim ProductionArray(0 to Openhours, 0 to 1) As Double
是相同的。请尝试使用ReDim ProductionArray(1 to Openhours, 1 to 1) As Double
,我认为这是你需要的。 - Tim Williams