Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get VBA to print an array into excel - array empty

Tags:

arrays

excel

vba

I have a small program that randomly generates different production rates. I did the program without arrays at first, where the values were printed at every row, which worked and was slow. So now I tried doing the same with arrays and my problem is printing the values:

My code (if you want to test-run it, it should be possible to just copy the code into vba and have one cell in the excel worksheet with the name "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

The problem at first was printing the values, but now it seem like the array "ProductionArray" is just printed as zeros.

I find this odd as I use

Cells.Find("Prodthishour").Offset(n, 1).Value2 = ProductionArray(n, 1)

to test-print the values next to the column that I really want it all to be printed in and also use

        For Each Item In ProductionArray
            Produced = Produced + Item
        Next

to sum everything, both giving me values, but still ProductionArray is printed as just zeros

(Edited)

like image 938
user2703642 Avatar asked Nov 20 '25 16:11

user2703642


1 Answers

You don't need the Transpose:

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

(assuming your array has the expected values - I didn't look at that part...)

like image 105
Tim Williams Avatar answered Nov 22 '25 07:11

Tim Williams