I created a user defined function (UDF) in C# and it works almost fine. This UDF is displaying information on an Excel worksheet and when the UDF is trying to overwrite a cell where is placed another call of the same UDF (not necessary the same, I have several UDF's) Excel is crashing with message "Microsoft Excel has stopped working". I found that overwriting the original Excel function doesn't lead to any problem or crashing. Here is a sample of my UDF:
[ExcelFunction(Name = "[functionName][1]", IsMacroType = true)]
public static string teGetHistorical(string cntry = "", string indctr = "", string startDate = "", string endDate = "")
{
string key = "myKeyString";
//
//here some if statements defining my url string
//
JArray o;
using (WebClient wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
var json = wc.DownloadString(url);
o = JArray.Parse(json);
}
if (o.Count == 0)
{
MessageBox.Show("No data provided for selected parameters");
}
else
{
Microsoft.Office.Interop.Excel.Application app = (Microsoft.Office.Interop.Excel.Application)ExcelDnaUtil.Application;
Microsoft.Office.Interop.Excel.Range currentCell = app.ActiveCell;
for (int i = 0; i < o.Count; i++)
{
for (int j = 0; j < names.Length; j++)
{
if (currentCell[i + 2, j + 1].HasFormula())
{
// here I'm detecting cell with formula and truing overpass this issue. Although tried
// currentCell[i + 2, j + 1].Clear(); and
// currentCell[i + 2, j + 1] = null;
currentCell[i + 2, j + 1].ClearFormats();
currentCell[i + 2, j + 1].ClearContents();
currentCell[i + 2, j + 1] = o[i][names[j]];
}
else
{
currentCell[i + 2, j + 1].ClearFormats();
currentCell[i + 2, j + 1].ClearContents();
currentCell[1, j + 1].Font.Bold = true;
if (j > 0)
{
currentCell[1, j + 1] = names[j];
}
currentCell[2 + i, j + 1] = o[i][names[j]];
}
}
}
}
return "Country";
}
Any suggestions how to handle this ?