C# Excel 函数 - 检测到无法访问的代码

标签 c# excel function unreachable-code

我正尝试在 C# 中创建一个函数类以用于 excel 自动化加载项。使用下面的简单代码,我想在与用户选择的颜色相匹配的范围内添加值(例如, sum Range("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 行返回“Unreachable code detected”。我给出的代码示例是我实际想要做的事情的简化示例,但很好地说明了我的观点。是我的代码有问题,还是我可以用更好的方式来避免这个问题?

谢谢, 里科。

为了总结这个问题,以下代码完全有效(更改 for(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;

它将退出,它无法到达其余代码。删除该行。

关于C# Excel 函数 - 检测到无法访问的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18316725/

相关文章:

Excel - 使用在单独单元格中输入的条件使用 SUMIFS (OR)

excel - "com_error: (-2147417851, ' 服务器抛出异常。 ', None, None)"

BASH:如何从函数中正确返回 true 和 false

c++ - 类函数更改类cpp中的其他数据

c - C 中参数数量未知的函数

c# - BackgroundWorker 问题(C# Windows 窗体)

c# - 如何更早发现不良端点?

c# - C#中的垃圾收集器问题

C# 如何在 Outlook 加载项中获取代表电子邮件地址的发送

excel - 如何根据另一列的值增加一列中的值