簡體   English   中英

C#Excel功能 - 檢測到無法訪問的代碼

[英]C# Excel Function - unreachable code detected

我正在嘗試在C#中創建一個函數類,以便在excel自動化加載項中使用。 使用下面的簡單代碼,我想要在與用戶選擇的顏色匹配的范圍內添加值(例如,和范圍(“A1:A10”),其中單元格顏色與“B1”相同) :colourSum(A1:A10,B1)。

    public double ColourSum(Range RangeToSum, Range cellContainingColourToSum)
    {
        double currentTotal = 0;
        //return 0; this code is edited from my original posting, due to posting error
        for (int i = 0; i < RangeToSum.Cells.Count;i++) //error at 'int i'
        {
            double iColour = RangeToSum.Interior.ColorIndex(i);
            if (iColour == cellContainingColourToSum.Interior.ColorIndex)
            {
                currentTotal = currentTotal + RangeToSum.Value2(i);
                //return currentTotal;

            }

        }
        return currentTotal;
    }

不幸的是,上面的代碼在第4行返回“檢測到無法訪問的代碼”。我給出的代碼示例是我實際想要做的一個簡化示例,但很好地說明了我的觀點。 我的代碼有問題,還是我可以用更好的方式來避免這個問題?

謝謝,Rico。

總結一下這個問題,下面的代碼完全有效(改為(int i ... with foreach(Range r ...):

    public double ColourSum(Range RangeToSum, Range cellContainingColourToSum)
    {
        double currentTotal = 0;
        foreach (Range r in RangeToSum)
        {
            double iColour = r.Interior.ColorIndex;
            if (iColour == cellContainingColourToSum.Interior.ColorIndex)
            {
                currentTotal = currentTotal + r.Value2;
            }
        }
        return currentTotal;
    }

你的代碼命中的那一分鍾:

return 0;

它將退出,它無法到達其余的代碼。 刪除該行。

當命中行return 0 ,該函數結束,之后不執行任何操作。 因此,它是無法訪問的代碼。 刪除此行以使函數正常運行。

在你進入循環之前你返回0。 這就是代碼無法訪問的原因。

return 0;

也許你的DLL沒有在輸出目錄中編譯和替換。 您必須清理重建所有代碼。 (如果您可以從輸出文件夾手動刪除所有內容,那將會很好)。

如果將此dll添加為項目引用,則刪除並重新添加項目引用。 可能是這樣的。

暫無
暫無

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

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