简体   繁体   English

Excel-VBA中的简单移动平均范围

[英]Simple moving average range in Excel-VBA

This code is just to calculate simple moving average. 该代码仅用于计算简单的移动平均线。 Opened an excel, created dummy array in C row from 1 to 20. I want to create a function for eg: SMA(C7,3) = which should give average of C5:C7. 打开一个excel,在C行中从1到20创建了一个虚拟数组。我想为例如创建一个函数:SMA(C7,3)=应该提供C5:C7的平均值。

Coming back to VBA after long time, not able to figure whats the error in the below code. 长时间后返回VBA,无法在下面的代码中找出错误。

Function sma1(rng As Range, N As Integer)
Set rng = rng.Resize(-N + 1, 0)
sma1 = Application.WorksheetFunction.average(rng)
End Function
  1. avoid using a cell name as a function 避免将单元格名称用作函数
  2. fixed the RESIZE() 修复了RESIZE()
  3. used an internal range variable 使用内部范围变量


Function smal(rng As Range, N As Integer) As Variant Dim rng2 As Range Set rng2 = rng.Resize(N, 1) smal = Application.WorksheetFunction.Average(rng2) End Function 函数smal(rng作为范围,N作为整数)作为变量Dim rng2作为范围集rng2 = rng.Resize(N,1)smal = Application.WorksheetFunction.Average(rng2)结束函数

EDIT#1: 编辑#1:

Based on Scott's comment: 根据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

I assume you want the column along side it to give you're SMA (as shown below?): 我假设您希望柱子旁边有SMA(如下所示?):

在此处输入图片说明

If so, the below will do it and drag it autocomplete it to the bottom of you column C array: 如果是这样,下面将执行此操作并将其自动完成,并将其拖动到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

Just an FYI this can be done with existing formula: 仅供参考,可以使用现有公式完成:

=IF(ROW(C1)<$E$1,"",AVERAGE(INDEX(C:C,ROW(C1)-$E$1+1):C1))

E1 contains the number of rows to include. E1包含要包括的行数。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM