UDF returns the same value everywhere

前端 未结 5 1921
闹比i
闹比i 2020-12-06 22:06

I am trying to code in moving average in vba but the following returns the same value everywhere.

Function trial1(a As Integer) As Variant
    Application.Vo         


        
5条回答
  •  余生分开走
    2020-12-06 23:00

    I believe that Application.ActiveCell is not what you should be using here. Application.ThisCell would be more appropriate assuming that "a" is the size of the subset and that the dataset is 1 column on the right. Moreover, I would simply use "WorksheetFunction.Average" instead of "Application.Sum" and I would add "Application.Volatile" so the average is recalculated whenever an update occurs on the worksheet.

    So one solution to your issue would be:

    Public Function Trial1(a As Integer) As Variant
      Application.Volatile
      Trial1 = WorksheetFunction.Average(Application.ThisCell(1, 2).Resize(a))
    End Function
    

    Another solution here would be to use an array formula entered with Control/Shift/Enter:

    Public Function MovAvg(dataset As Range, subsetSize As Integer)
      Dim result(), subset As Range, i As Long
      ReDim result(1 To dataset.Rows.count, 1 To 1)
      Set subset = dataset.Resize(subsetSize)
    
      For i = 1 To dataset.Rows.count
        result(i, 1) = WorksheetFunction.Average(subset.offset(i - 1))
      Next
    
      MovAvg = result
    End Function
    

    And to use this array function:

    • Select the range where all the results will be written (should be the size of your dataset)
    • Type "=MovAvg(A1:A100, 2)" where A1:A100 is the source of the data and 2 the size of the subset
    • Press Ctrl+Shift+Enter

提交回复
热议问题