I have created an Automation Add-in for Excel,implemented as a C# class library, which contains a UDF wrapper.(I do not use VSTO)
What I would like to do in my UDF, is to:
1>get the cell address where the formula was entered;
2>set the formula of that cell to one of my own;
I have already done point 1> as follows:
Microsoft.Office.Interop.Excel.Application excelApp = (Microsoft.Office.Interop.Excel.Application)Marshal.GetActiveObject("Excel.Application");
Microsoft.Office.Interop.Excel.Range target = (Microsoft.Office.Interop.Excel.Range)excelApp.get_Caller(System.Type.Missing);
string cellAddress = target.get_Address(Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1, Missing.Value, Missing.Value);
//Perform some operations based on address
//Assign a formula to my cell (This does not work !)
target.Formula ="=SUM(2,2)"
This should work according to the MSDN documentation from here.
What am I doing wrong ? Is there any other way I can set the formula of the cell?
Thanks,
A UDF can only return a value to its calling cell – it is not allowed to overwrite its own formula (or alter the contents of any other cell). You would need to create a command to do that.