简体   繁体   English

如何从Excel工作表调用VBA函数

[英]How to call VBA Function from excel sheet

Whenever I try to call the function from a cell by typing =MAE() it won't run, always returns a 0. Can someone help guide me? 每当我尝试通过键入= MAE()从单元格调用该函数时,该函数均不会运行,始终返回0。有人可以帮助我吗? The function below works fine as a sub procedure. 下面的功能可以很好地作为子过程。 It needs to loop through an entire column and calculate the absolute average 它需要遍历整个列并计算绝对平均值

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

I would avoid selecting the cells when looping through them. 我将避免在遍历它们时选择它们。
With the following code it works for me: 使用以下代码,它对我有用:

...
' 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

... ...

You rarely have to select or activate cells. 您很少需要选择或激活单元格。 Never select or activate from a UDF. 切勿从UDF中选择或激活它。

Use Application.Volatile so that your function will recalculate as values change. 使用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

This might be more useful. 这可能更有用。

MAE(A2:A7) 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM