6

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.

Kevin M
  • 801
  • 3
  • 9
  • 14
  • 1
    Possible duplicate of [Using a variable to define a range](http://stackoverflow.com/questions/34714578/using-a-variable-to-define-a-range/34715205#34715205). –  Jan 11 '16 at 23:57

2 Answers2

11

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
Fadi
  • 3,302
  • 3
  • 18
  • 41
4

You don't need any loops to move an array to memory. For example:

Sub Array2Range()
   Dim Directory(1 To 182, 1 To 6) As Variant
   Dim rng As Range, i As Long, j As Long

   For i = 1 To 6
      For j = 1 To 182
         Directory(j, i) = i * j
      Next j
   Next i

   Set rng = Sheets("List").Range("A1:F182")

   rng = Directory

End Sub

will produce:

enter image description here

Gary's Student
  • 95,722
  • 10
  • 59
  • 99