如何使用值填充二维数组,然后将结果放入范围

时间:2013-10-14 23:53:33

标签: arrays excel vba range

这是一个问题:“假设你的程序使用值填充一个名为results的大型二维数组,并且你希望它将这些值转储到Excel范围内。例如,如果结果是m乘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

我真的需要一些帮助来解决这个问题我完全迷失了

2 个答案:

答案 0 :(得分:2)

这将使用m行和n列填充数组,然后将其全部传输到从A1的单元格ActiveSheet开始的范围内:

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

答案 1 :(得分:0)

假设您在此之前将数据填入其他地方,则可以使用

Cells(X, Y).Value=MyArray(X, Y)