我有一个小程序随机生成不同的生产率。我在没有数组的情况下完成了程序,其中值在每一行都打印出来,但是工作起来很慢。所以现在我尝试对数组做同样的事情,我的问题是打印值:
我的代码(如果你想测试运行它,应该可以将代码复制到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 :(得分:2)
您不需要转置:
Cells.Find("Prodthishour").Offset(1, 0) _
.Resize(UBound(ProductionArray, 1),1).Value = ProductionArray
(假设你的数组有预期值 - 我没看过那部分......)
答案 1 :(得分:0)
我现在想知道是否使用
正确定义矩阵ReDim ProductionArray(Openhours, 1) As Double
对我来说奇怪的部分是当我使用
时ProductionArray(n, 1) = A + Minimumatprod + Rnd() * (Maxlimit - Minimumatprod - A)
阵列打印为零,但使用
Cells.Find("Prodthishour").Offset(n, 1).Value2 = ProductionArray(n, 1)
打印每个步骤的值(作为检查错误的方法),给我完美的值,但是当我尝试在最后打印时,这些在某些方面不存在于ProductionArray中。