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



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

我真的需要一些帮助来弄清楚我完全迷路了

这会用 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

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

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

最新更新