2

我有一个随机生成不同生产率的小程序。起初,我在没有数组的情况下编写了程序,在每一行都打印了值,这很有效,而且速度很慢。所以现在我尝试对数组做同样的事情,我的问题是打印值:

我的代码(如果你想测试运行它,应该可以将代码复制到 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 仍然打印为零

(已编辑)

4

2 回答 2

2

你不需要转置:

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

(假设您的数组具有预期值 - 我没有看那部分......)

于 2013-09-05T22:05:15.423 回答
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 中。

于 2013-09-06T15:57:57.650 回答