簡體   English   中英

調試時Excel單元格中的答案不值

[英]Answer in Excel cell is not value while debugging

我有一個試圖在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

是的,所以我更改了幾件事,顯式聲明了變量等,並得到了這一點:

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

這似乎為我計算了平均罰款。 我想知道由編譯器推斷變量類型引起的錯誤調試是否很困難。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM