ERROR! (Using Excel's named ranges from C#)
- by mcoolbeth
In the following, I am trying to persist a set of objects in an excel worksheet. Each time the function is called to store a value, it should allocate the next cell of the A column to store that object.
However, an exception is thrown by the Interop library on the first call to get_Range(). (right after the catch block)
Does anyone know what I am doing wrong?
private void AddName(string name, object value)
{
Excel.Worksheet jresheet;
try
{
jresheet = (Excel.Worksheet)_app.ActiveWorkbook.Sheets["jreTemplates"];
}
catch
{
jresheet = (Excel.Worksheet)_app.ActiveWorkbook.Sheets.Add(Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
jresheet.Visible = Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetVeryHidden;
jresheet.Name = "jreTemplates";
jresheet.Names.Add("next", "A1", true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
Excel.Range cell = jresheet.get_Range("next", Type.Missing);
cell.Value2 = value;
string address = ((Excel.Name)cell.Name).Name;
_app.ActiveWorkbook.Names.Add(name, address, false,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
cell = cell.get_Offset(1, 0);
jresheet.Names.Add("next", ((Excel.Name)cell.Name).Name, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}