简体   繁体   English

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

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

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. 我正在尝试将大小为183x6的2D数组分配给新工作表,使用数组的值填充A1:G182中的空白单元格。 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. 我感谢您的帮助。

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

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: 将产生:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM