gpt4 book ai didi

arrays - 让 VBA 将数组打印到 excel - 数组为空

转载 作者:行者123 更新时间:2023-12-04 19:48:41 26 4
gpt4 key购买 nike

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

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

(已编辑)

最佳答案

你不需要转置:

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

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

关于arrays - 让 VBA 将数组打印到 excel - 数组为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18646273/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com