【问题标题】:Simple moving average range in Excel-VBAExcel-VBA中的简单移动平均范围
【发布时间】:2016-09-12 14:12:15
【问题描述】:

这段代码只是为了计算简单的移动平均线。打开一个 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中的0改为1。它与 offset() 不同。
  • 仅供参考,this answer 说明了您收到重命名函数的建议的原因。

标签: vba excel average


【解决方案1】:
  1. 避免将单元格名称用作函数
  2. 修复了RESIZE()
  3. 使用了内部范围变量


函数 smal(rng As Range, N As Integer) As Variant 调暗 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

【讨论】:

  • @ScottCraner 谢谢
【解决方案2】:

我假设您希望它旁边的列显示您是 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

【讨论】:

    【解决方案3】:

    仅供参考,这可以使用现有公式完成:

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

    E1 包含要包含的行数。

    【讨论】:

      猜你喜欢
      • 2017-10-18
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      相关资源
      最近更新 更多