如何用值填充二维数组,然后将结果放入范围 [英] How do I fill a 2 dimensional Array with Values and then put the results into a range

查看:106
本文介绍了如何用值填充二维数组,然后将结果放入范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是一个问题:假设您的程序用值填充了一个称为结果的大型二维数组,并且您希望它将这些值转储到Excel范围内。例如,如果结果为m×n,则将就像程序将值转储到m行和n列的范围内一样。一种方式是使用两个嵌套循环将数据一次转储一个元素到适当的单元格中。

Here is the question: "Suppose your program fills a large two-dimensional array called results with values, and you would like it to dump these values into an Excel range. For example, if results is m by n, you would like the program to dump the values into a range with m rows and n columns. One way is to use two nested loops to dump the data one element at a time into the appropriate cell."

到目前为止,我得到的是:

What I've got so far:

    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

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

I really need some help figuring this out I'm totally lost

推荐答案

这将用m行n列填充数组然后将其全部转移到从 ActiveSheet 的单元格 A1 开始的范围:

This fills the array with m rows and n columns and then transfers it all into a range starting in cell A1 of the 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

这篇关于如何用值填充二维数组,然后将结果放入范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆