Search code examples
arraysexcelvbaoptimizationvariant

VBA: Write array to sheet in a block (one memory access)


I have a large array (45000 elements) that i need to write down in an excel sheet. However this is taking way to long when looping over the values (requesting a memory access for each value)

(I have already disabled features like screen updating)

I've found some ways to do it using the Variant type (french : https://www.lecfomasque.com/vba-rediger-des-macros-plus-rapides/) However i must be messing up at some point, see example code

Sub test()
    Dim table(4) As Variant
    Dim writeArray() As Variant


    table(0) = 0
    table(1) = 1
    table(2) = 2
    table(3) = 3
    table(4) = 4

    writeArray = table

    'Supposed to write 0 to A1, 1 to A2,... but not working that way
    Range("A1:A5").Value = writeArray

End Sub

This code writes only the first value (0) to the whole range, even if the variant writearray contains also the other values (1,2,3,4).

Any idea (without a memory request for each value) on how to solve this is welcome, Thank you ^-^

EDIT (SOLUTION)-----------------------

Paul's (transpose) and Mikku's (2D-array) solutions seem to work and both provide an tenfold reduction of execution time in my case. The transpose is slighly faster on average.


Solution

  • On this site I found this useful little piece...

    Dim Destination As Range
    Set Destination = Range("K1")
    Destination.Resize(UBound(Arr, 1), UBound(Arr, 2)).Value = Arr
    

    You can transpose the array when writing to the worksheet:

    Set Destination = Range("K1")
    Destination.Resize(UBound(Arr, 2), UBound(Arr, 1)).Value = Application.Transpose(Arr)