[英]Simple moving average range in Excel-VBA
該代碼僅用於計算簡單的移動平均線。 打開一個excel,在C行中從1到20創建了一個虛擬數組。我想為例如創建一個函數:SMA(C7,3)=應該提供C5:C7的平均值。
長時間后返回VBA,無法在下面的代碼中找出錯誤。
Function sma1(rng As Range, N As Integer)
Set rng = rng.Resize(-N + 1, 0)
sma1 = Application.WorksheetFunction.average(rng)
End Function
RESIZE()
函數smal(rng作為范圍,N作為整數)作為變量Dim rng2作為范圍集rng2 = rng.Resize(N,1)smal = Application.WorksheetFunction.Average(rng2)結束函數
編輯#1:
根據Scott的評論:
Function smal(rng As Range, N As Integer) As Variant
Dim rng2 As Range
Set rng2 = rng.Offset(1 - N, 0).Resize(N, 1)
smal = Application.WorksheetFunction.Average(rng2)
End Function
我假設您希望柱子旁邊有SMA(如下所示?):
如果是這樣,下面將執行此操作並將其自動完成,並將其拖動到C列數組的底部:
Sub SMA3()
Range("D7").FormulaR1C1 = "=AVERAGE(R[-2]C[-1]:RC[-1])" 'This is a relative reference (left one cell and up two cells) - This give your three inputs
Range("D7").AutoFill Destination:=Range("D7:D" & Range("C1048576").End(xlUp).Row) 'Autofills the SMA
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.