获取VBA将数组打印到Excel中 – 数组为空

我有一个小程序,随机产生不同的生产率。 我开始没有使用数组的程序,数据在每一行打印,工作起来很慢。 所以现在我试着做与数组相同的,我的问题是打印值:

我的代码(如果你想testing运行它,应该可以将代码复制到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) 

testing打印列中的值,我真的希望全部打印并使用

  For Each Item In ProductionArray Produced = Produced + Item Next 

总结一切,都给我的价值观,但仍然ProductionArray打印为零

(编辑)的

你不需要移调:

  Cells.Find("Prodthishour").Offset(1, 0) _ .Resize(UBound(ProductionArray, 1),1).Value = ProductionArray 

(假设你的数组有预期的值 – 我没有看那部分…)

我现在想知道我是否正确使用matrix定义

 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中出现。