Hi Mark,
Excel does not allow you to alter the sheet inside a UDF calculation.
That makes sense if you consider how Excel is trying to keep track of the dependencies of different parts of the sheet, to provide fast and correct recalculation if anything changes.
If the functions called from any cell might be writing elsewhere in the sheet, it becomes impossible to know where the values you see on the sheet come from, which ones can be changes without being overwritten be a recalculation,
etc. You would basically break the whole spreadsheet model and as such, you're heading for an mess. So Excel doesn't let you do that.
It's better to find a different way, like having the 'target' range depend on a function that depends on the input names range as its argument values. Or a button that the users press to do the processing, which is thus not
tied into the spreadsheet calculation.
If you still insist on going down this bad and dangerous road, Excel-DNA does provide a helper method (ExcelAsyncUtil.QueueAsMacro) to schedule some code to run in a macro context, as soon as possible (typically after the
calculation completes). This method can be called from any thread and from any context, including from your UDF in a calculation context.
So your function might say:
public object DangerousFunctionThatWillSurelyMakeAMess(double valueToWriteToA1)
{
ExcelAsyncUtil.QueueAsMacro( () =>
{
ExcelReference target = new ExcelReference(0, 0, 0, 0, "Sheet1");
target.SetValue(valueToWriteToA1);
});
return "Bad things will happen...";
}
-Govert