VBA将数据数据保存到电子表格的给定列

我在VBA中有一个函数来计算移动平均值,如下所示:

Function calculateMovingAverage(myDate As Date, myDateVector As Range, myPrices As Range, myWindow As Integer) ' use the series of prices to calculate the moving average over a number of days ' ie if myWindow=50 then calculate the 50 days moving average calculateMovingAverage = movingAvg End Function 

该函数将结果保存在具有1000个元素的数组中。 我怎样才能使代码保存这个数组从单元格A1到单元格A1000?

通过.transpose

 Range("A1:A1000").Value = Application.Transpose(movingAvg) 

(dynamicRange("A1:A" & UBound(movingAvg) + 1)...

你有没有尝试过 …

 Range("A1:A1000").Value = movingAvg 

我相信你可以直接分配一个数组的大小正确的范围。


否则,你可以遍历这些值并单独添加它们…

 For i = 1 to 1000 cells(i,1).Value = movingAvg(i) Next i 

请注意,您可能需要根据您使用Option Base 0Option Base 0声明来使用i的值。


正如亚历克斯所提到的,因为数组是1维的,Excel可能会认为它应该是水平输出的,而不是垂直的,在这种情况下,您需要使用Transpose 。 感谢Alex:O)