Excel VBA函数将数组打印到工作簿
我编写了一个宏,它采用二维数组,并将其“打印”到 Excel 工作簿中的等效单元格。
有没有更优雅的方法来做到这一点?
Sub PrintArray(Data, SheetName, StartRow, StartCol)
Dim Row As Integer
Dim Col As Integer
Row = StartRow
For i = LBound(Data, 1) To UBound(Data, 1)
Col = StartCol
For j = LBound(Data, 2) To UBound(Data, 2)
Sheets(SheetName).Cells(Row, Col).Value = Data(i, j)
Col = Col + 1
Next j
Row = Row + 1
Next i
End Sub
Sub Test()
Dim MyArray(1 To 3, 1 To 3)
MyArray(1, 1) = 24
MyArray(1, 2) = 21
MyArray(1, 3) = 253674
MyArray(2, 1) = "3/11/1999"
MyArray(2, 2) = 6.777777777
MyArray(2, 3) = "Test"
MyArray(3, 1) = 1345
MyArray(3, 2) = 42456
MyArray(3, 3) = 60
PrintArray MyArray, "Sheet1", 1, 1
End Sub
I've written a macro that takes a 2 dimensional array, and "prints" it to equivalent cells in an excel workbook.
Is there a more elegant way to do this?
Sub PrintArray(Data, SheetName, StartRow, StartCol)
Dim Row As Integer
Dim Col As Integer
Row = StartRow
For i = LBound(Data, 1) To UBound(Data, 1)
Col = StartCol
For j = LBound(Data, 2) To UBound(Data, 2)
Sheets(SheetName).Cells(Row, Col).Value = Data(i, j)
Col = Col + 1
Next j
Row = Row + 1
Next i
End Sub
Sub Test()
Dim MyArray(1 To 3, 1 To 3)
MyArray(1, 1) = 24
MyArray(1, 2) = 21
MyArray(1, 3) = 253674
MyArray(2, 1) = "3/11/1999"
MyArray(2, 2) = 6.777777777
MyArray(2, 3) = "Test"
MyArray(3, 1) = 1345
MyArray(3, 2) = 42456
MyArray(3, 3) = 60
PrintArray MyArray, "Sheet1", 1, 1
End Sub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
与其他答案相同的主题,保持简单
On the same theme as other answers, keeping it simple
创建一个变量数组(最简单的方法是读取变量变量中的等效范围)。
然后填充数组,并将数组直接赋值给范围。
变体数组最终将成为二维矩阵。
Create a variant array (easiest by reading equivalent range in to a variant variable).
Then fill the array, and assign the array directly to the range.
The variant array will end up as a 2-D matrix.
一种更优雅的方法是一次分配整个数组:
但要注意:它最多只能处理大约 8,000 个单元格的大小。然后 Excel 抛出一个奇怪的错误。最大大小不是固定的,并且不同的 Excel 安装有很大不同。
A more elegant way is to assign the whole array at once:
But watch out: it only works up to a size of about 8,000 cells. Then Excel throws a strange error. The maximum size isn't fixed and differs very much from Excel installation to Excel installation.
正如其他人所建议的,您可以直接将二维数组写入工作表上的范围,但是如果您的数组是一维的,那么您有两个选择:
这是描述这两个选项的示例:
注意:转置将渲染逐列输出,要获得逐行输出,请再次转置它 - 希望这是有道理的。
华泰
As others have suggested, you can directly write a 2-dimensional array into a Range on sheet, however if your array is single-dimensional then you have two options:
Here is an example depicting both options:
Note: Transpose will render column-by-column output, to get row-by-row output transpose it again - hope that makes sense.
HTH
我测试过的版本
My tested version
您可以定义一个 Range、数组的大小并使用它的 value 属性:
You can define a Range, the size of your array and use it's value property: