UDF returns the same value everywhere

前端 未结 5 1880
闹比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条回答
  •  萌比男神i
    2020-12-06 22:59

    The ActiveCell property does not belong in a UDF because it changes. Sometimes, it is not even on the same worksheet.

    If you need to refer to the cell in which the custom UDF function resides on the worksheet, use the Application.Caller method. The Range.Parent property can be used to explicitly identify the worksheet (and avoid further confusion) in a With ... End With statement.

    Function trial1(a As Integer) As Variant
    
        Application.Volatile
        Dim rng As Range
        with Application.Caller.Parent
            Set rng = .Range(.Cells(Application.Caller.Row, 2), _
                             .Cells(Application.Caller.Row - a + 1, 2))
            trial1 = (Application.Sum(rng)) * (1 / a)
        end with
    
    End Function
    

    You've applied the Application.Volatile¹ method but allowed the range to be averaged to default to the ActiveSheet property by not explcitly specifying the parent worksheet.

    The average is computed with the Excel Application object returning a SUM function's result and some maths. The same could have been returned in one command with the worksheet's AVERAGE function but blank cells would be handled differently.

            trial1 = Application.Average(rng)
    

    ¹ Volatile functions recalculate whenever anything in the entire workbook changes, not just when something that affects their outcome changes.

提交回复
热议问题