Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA - Assign Values of 2D Array to Range of Cells

Tags:

arrays

excel

vba

I'm trying to assign a 2D array of size 183x6 to a new sheet, populating the blank cells from A1:G182 with the values of the array. For reference, my array is called "Directory" and the empty sheet I want to populate is called "List".

I've tried two different approaches, one by explicitly assigning the specified range to the array as such:

Worksheets("List").Range(Cells(1,1), Cells(UBound(Directory, 1) + 1, UBound(Directory, 2) + 1)) = Directory

And also by trying to iterate through each entry in the array:

For i = 0 To UBound(Directory, 1)
    For j = 0 To UBound(Directory, 2)
        Worksheets("List").Range(Cells(i + 1, j + 1), Cells(i + 1, j + 1)) = Directory(i,j)
    Next j
Next i

In both cases, I get the error:

Run-time error '1004':
Application-defined or object defined error.

Any ideas what could be happening? I appreciate your help.

like image 506
Kevin M Avatar asked Jan 11 '16 23:01

Kevin M


People also ask

How do I assign a range in Excel VBA?

To set the reference, we need to use the “SET” keyword and enter the cell addresses using the RANGE object. The variable “Rng” refers to the cells A1 to B5. Instead of writing the cell address Range (“A1:B5”), we can use the variable name “Rng.” It will insert the mentioned value from the A1 to the B5 cells.


1 Answers

Try:

Worksheets("List").Range("A1").Resize(UBound(Directory, 1) + 1, UBound(Directory, 2) + 1).Value = Directory

Or:

For i = 0 To UBound(Directory, 1)
    For j = 0 To UBound(Directory, 2)
        Worksheets("List").Range(Worksheets("List").Cells(i + 1, j + 1), Worksheets("List").Cells(i + 1, j + 1)) = Directory(i,j)
    Next j
Next i
like image 102
Fadi Avatar answered Sep 20 '22 22:09

Fadi