Excel VBA - 将2D数组的值分配给单元格范围

时间:2022-08-10 21:34:43

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".

我正在尝试将大小为183x6的2D数组分配给新工作表,使用数组的值填充A1:G182中的空白单元格。作为参考,我的数组称为“目录”,我要填充的空表称为“列表”。

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.

有什么想法会发生什么?我感谢您的帮助。

2 个解决方案

#1


3  

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

#2


3  

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:

将产生:

Excel VBA  - 将2D数组的值分配给单元格范围

#1


3  

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

#2


3  

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:

将产生:

Excel VBA  - 将2D数组的值分配给单元格范围