【问题标题】:How do I fill a 2 dimensional Array with Values and then put the results into a range如何用值填充二维数组,然后将结果放入范围
【发布时间】:2013-10-22 15:53:37
【问题描述】:
问题如下:“假设您的程序用值填充了一个名为 results 的大型二维数组,并且您希望它将这些值转储到 Excel 范围内。例如,如果 results 是 m x n,您将就像程序将值转储到具有 m 行和 n 列的范围中。一种方法是使用两个嵌套循环将数据一次一个元素转储到适当的单元格中。
到目前为止我得到了什么:
Dim MyArray(m, n) As Long
Dim X as Long
Dim Y as Long
For X = 1 To m
For Y = 1 To n
MyArray(X, Y) = Cells(X, Y).Value
Next Y
Next X
我真的需要一些帮助来弄清楚我完全迷路了
【问题讨论】:
标签:
arrays
excel
vba
range
【解决方案1】:
这会用 m 行和 n 列填充数组,然后将其全部传输到以ActiveSheet 的单元格A1 开始的范围内:
Sub FillRangeFromArray()
Dim m As Long
Dim n As Long
Dim x As Long
Dim y As Long
Dim MyArray() As String
'set the row and column dimensions
m = 100
n = 5
'redimension the array now that you have m and n
ReDim MyArray(1 To m, 1 To n)
'whenever possible lbound and ubound (first to last element)
'to loop through arrays, where
'MyArray,1 is the first (row) element and MyArray,2
'is the second (column) element
For x = LBound(MyArray, 1) To UBound(MyArray, 1)
For y = LBound(MyArray, 2) To UBound(MyArray, 2)
MyArray(x, y) = x & "-" & y
Next y
Next x
'fill the range in one fell swoop
'Resize creates a range resized to
'm rows and n columns
ActiveSheet.Range("A1").Resize(m, n).Value = MyArray
End Sub
【解决方案2】:
假设您在此之前将数据填充到其他地方,您可以使用
Cells(X, Y).Value=MyArray(X, Y)