vba 如何用值填充二维数组,然后将结果放入一个范围内
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19371139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I fill a 2 dimensional Array with Values and then put the results into a range
提问by user2880722
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."
这里的问题是:“假设您的程序用值填充了一个名为 results 的大型二维数组,并且您希望它将这些值转储到 Excel 范围中。例如,如果结果是 m × n,您希望该程序将值转储到具有 m 行和 n 列的范围中。一种方法是使用两个嵌套循环将数据一次一个元素转储到适当的单元格中。”
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
我真的需要一些帮助来解决这个问题 我完全迷失了
回答by Doug Glancy
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
:
这种填充具有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
回答by nutsch
Assuming you fill your data somewhere else before that, you can just use
假设您在此之前在其他地方填充数据,您可以使用
Cells(X, Y).Value=MyArray(X, Y)