[英]How to call VBA Function from excel sheet
每當我嘗試通過鍵入= 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
我將避免在遍歷它們時選擇它們。
使用以下代碼,它對我有用:
...
' 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
...
您很少需要選擇或激活單元格。 切勿從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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.