Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Excel Function - unreachable code detected

I'm attempting to create a function class in C# for use in an excel Automation add-in. Using the simple code below, I was wanting to add the values in a range that match the colour that the user selects (for example, sum Range("A1:A10") where the cell colour is the same as "B1" would be: 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;
    }

Unfortunately, the above code returns "Unreachable code detected" on line 4. The code example I've given is a simplified example of what I actually want to do but illustrates my point quite well. Is there a problem with my code, or can I write in a better way to avoid this problem?

Thanks, Rico.

To conclude the question, the following code worked completely (changing 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;
    }
like image 766
user1866659 Avatar asked Jun 18 '26 15:06

user1866659


2 Answers

The minute your code hits the line:

return 0;

it will exit, there's no way for it to reach the rest of the code. Remove the line.

like image 132
GrandMasterFlush Avatar answered Jun 20 '26 04:06

GrandMasterFlush


When the line return 0 is hit, the function ends, and nothing after that is executed. Hence, it is unreachable code. Remove this line to get the function to behave properly.

like image 33
Trenin Avatar answered Jun 20 '26 05:06

Trenin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!