我正在寻找美观而优雅的解决方案来实现下面的工作代码。经过多次搜索和尝试,我找不到它,因为VBA理由对我来说有点神奇。
循环代码:
Public Sub Array2Range(My2DArray As Variant, aWS As Worksheet)
' Ref : https://stackoverflow.com/questions/6063672/excel-vba-function-to-print-an-array-to-the-workbook
' Ref : http://www.ozgrid.com/VBA/sort-array.htm
' Ref : https://www.mrexcel.com/forum/excel-questions/14194-vba-arrays-examples-please-how-read-range-th.html
' Ref : https://bettersolutions.com/excel/cells-ranges/vba-working-with-arrays.htm
' Usage : Array2Range MyArray, aWS
Dim i, j As Integer
Dim elt As Variant
For i = 1 To UBound(My2DArray) - LBound(My2DArray) + 1
j = 1
For Each elt In My2DArray(i)
aWS.Cells(j, i) = elt
j = j + 1
Next elt
Next i
End Sub
感谢您的支持和想法。
答案 0 :(得分:1)
这消除了一个循环:
Public Sub Array2Range(My2DArray As Variant, aWS As Worksheet)
' Ref : https://stackoverflow.com/questions/6063672/excel-vba-function-to-print-an-array-to-the-workbook
' Ref : http://www.ozgrid.com/VBA/sort-array.htm
' Ref : https://www.mrexcel.com/forum/excel-questions/14194-vba-arrays-examples-please-how-read-range-th.html
' Ref : https://bettersolutions.com/excel/cells-ranges/vba-working-with-arrays.htm
' Usage : Array2Range MyArray, aWS
Dim i as Long
For i = 1 To UBound(My2DArray) - LBound(My2DArray) + 1
aWS.Cells(1, i).Resize(UBound(My2DArray(i))).Value = Application.Transpose(My2DArray(i))
Next i
End Sub
答案 1 :(得分:1)
类似,但有点不同的选择:
Sub ArrayToRange(jaggedArray, cell As Range): Dim subArray
For Each subArray In jaggedArray
cell.Resize(UBound(subArray), 1) = Application.Transpose(subArray)
Set cell = cell(, 2)
Next
End Sub