如何从excel表调用VBA函数

时间:2016-06-23 07:15:03

标签: excel vba

每当我尝试通过键入= MAE()来调用单元格中的函数时,它就不会运行,总是返回0.有人可以帮助指导我吗?以下函数作为子过程正常工作。它需要遍历整个列并计算绝对平均值

Function MAE() As Double
    Dim cell As Object
    Dim nRows As Integer
    Dim total As Double
    Dim i As Integer
    Dim mean As Double
    total = 0

    ' Count the rows
    With wsData.Range("A2")
        nRows = Range(.Offset(0, 0), .End(xlDown)).Rows.Count
    End With
    'loop through rows, add to total, select next cell
    Range("A2").Select
    For i = 0 To nRows
        total = total + Abs(ActiveCell.Value)
        ActiveCell.Offset(1, 0).Select
    Next i

    MAE = total / (nRows)
End Function

2 个答案:

答案 0 :(得分:0)

我会避免在循环时选择单元格 使用以下代码对我有用:

...
' Count the rows
With ActiveSheet.Range("A2")
    nRows = Range(.Offset(0, 0), .End(xlDown)).Rows.Count
End With

'loop through rows, add to total, select next cell
For i = 0 To nRows
    total = total + Abs(ActiveSheet.Range("A2").Offset(i, 0).Value)
Next i

...

答案 1 :(得分:0)

您很少需要选择或激活单元格。切勿从UDF中选择或激活。

使用Application.Volatile,以便在值发生变化时重新计算您的函数。

Function MAE() As Double
    Dim cell As Object
    Dim rCells As Range
    Application.Volatile
    With wsData.Range("A2")
        Set rCells = Range(.Offset(0, 0), .End(xlDown))
        For Each cell In rCells
            total = total + Abs(cell.value)
        Next cell
    End With

    MAE = total / rCells.Count
End Function

这可能更有用。

  

MAE(A2:A7)

Function MAE(rCells As Range) As Double
    Dim cell As Object

    Application.Volatile

    For Each cell In rCells
        total = total + Abs(cell.value)
    Next cell

    MAE = total / rCells.Count
End Function