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;
}
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.