【问题标题】:Formula to compute the average of calculated values using elements of an array, in VBA在 VBA 中使用数组元素计算计算值平均值的公式
【发布时间】:2023-03-14 03:19:01
【问题描述】:

我正在尝试在 VBA 中创建一个公式。

我有一个数组,比如说 [A,B,C,D]。
我想要一个函数返回以下公式 =average(A/B,B/C,C/D)

我稍微简化了这一点,因为我的范围会很长。
我需要公式一直持续到范围的末尾,这就是我卡住的地方。

【问题讨论】:

  • 加载变量数组中的值。循环变体数组并加载另一个变体数组,其值除以当前项目的 +1。然后平均输出变量数组。
  • 现在,我不明白A,B,C,D 代表什么。考虑一下:使​​用VBA 我想在E 列中从第2 行到最后一行写以下公式:=AVERAGE(A2/B2,B2/C2,C2/D2)。你能解释一下前一个问题和你的问题之间的区别吗?

标签: vba function excel-formula


【解决方案1】:

基于斯科特的评论。这是实现:

编辑:根据 Scott 的建议,无需 redim preserve

已添加行:ReDim resultValues(1 To UBound(sourceValues) - 1)

Public Function CalcAvg(ByVal sourceRange As Range) As Variant

    Dim sourceValues As Variant
    sourceValues = Application.Transpose(sourceRange.Value)

    Dim resultValues() As Variant
    Dim counter As Long
    ReDim resultValues(1 To UBound(sourceValues) - 1)
    For counter = 1 To UBound(sourceValues) - 1
        
        resultValues(counter) = sourceValues(counter) / sourceValues(counter + 1)
    
    Next counter
    
    CalcAvg = Application.Average(resultValues)

End Function

让我知道它是否有效

【讨论】:

  • 感谢@ScottCraner
猜你喜欢
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2014-05-14
相关资源
最近更新 更多