Hi Bhaumik,
Excel does not allow changes to be made to the sheet from inside a user-defined function.
(The AddComment call is unusual, in that it seems to work when called from functions.)
So what you want to do is quite hard.
You need to set up the work to run in a macro context after the calculation is complete, where you can then do the formatting updates.
Excel-DNA has a helper to achieve this - ExcelAsyncUtil.QueueAsMacro(...).
But then there are further complications. You need to remember where the function was called from, so that you can use it later in the macro.
(The ActiveCells that you shown in the example is not always the one you want, it refers to the cell currently selected in the sheet and this might be different from the "Current" cell, which is the one busy calculating your function.)
I prefer to use the C API (and the ExcelReference) in the function part itself, so I convert to a Range only when the macro is running.
So you also need to convert the ExcelReference object you get as the 'caller' inside the function to a COM Range object to make the update easy.
The code might look like this:
public static double SetGrayIfLarge(double input)
{
int colorIndex = input > 100 ? 15 : 0;
ExcelReference caller = XlCall.Excel(XlCall.xlfCaller) as ExcelReference;
if (caller != null)
{
// We were called from a cell (and not VBA or something etc.)
ExcelAsyncUtil.QueueAsMacro(() =>
{
// This is running in a macro context, after the calculation has completed.
// The caller and colorIndex variables have been captured and passed along
// as part of the delegate that was enqueued.
Application Application = (Application)ExcelDnaUtil.Application;
string callerAddress = (string)XlCall.Excel(XlCall.xlfReftext, caller, true);
Range callerRange = Application.Range[callerAddress];
callerRange.Interior.ColorIndex = colorIndex;
});
}
return input;
}
-Govert