我有一个我想在Excel 2011工作表中使用的自定义公式。我们的想法是使用一些自定义逻辑来计算一系列单元格的平均值。当我在Excel中单步执行调试器时,公式运行完美。
但是,当我将公式放在工作表上的单元格中(即=SuperAverage(K4:K17)
)时,我得到0或#VALUE
。我正在运行公式,其范围与我在调试器中执行时的确切范围相同,但我得到了不同的答案。
为什么会这样?我试过手动重新计算单元格,但错误仍然存在。
Function SuperAverage(r) As Double
Dim total_sum, total_count As Integer
total_sum = 0
total_count = 0
For Each c In r.Cells
If Not IsHidden(c) And c.value <> 0 Then 'IsHidden is another custom function irrelevant to this question
total_count = total_count + 1
total_sum = total_sum + c.value
End If
Next
If total_count = 0 Then
SuperAverage = 0
Else
SuperAverage = total_sum / total_count
End If
End Function
'test function to step through the debugger
Function Test()
Dim r As range
Set r = Worksheets("Hours").range("K4:K17")
Dim result As Double
result = SuperAverage(r)
End Function
答案 0 :(得分:1)
是的,所以我改变了一些事情,明确地声明变量等,并得到这个:
Option Explicit
Function SuperAverage(ByVal r As Range) As Double
Dim total_sum As Integer
Dim total_count As Integer
total_sum = 0
total_count = 0
Dim c As Variant
For Each c In r.Cells
If Not IsHidden(c) And c.Value <> 0 Then 'IsHidden is another custom function irrelevant to this question
total_count = total_count + 1
total_sum = total_sum + c.Value
End If
Next
If total_count = 0 Then
SuperAverage = 0
Else
SuperAverage = total_sum / total_count
End If
End Function
这似乎计算了我的平均罚款。我想知道编译器推断变量类型是否会导致调试错误。