Nicolas Fuerer
Posts: 6
Joined: 2014-06-26
|
Hello
Im trying to add named ranges in excel from C#. When I create a normal Excel-AddIn-Project in Visual Studio, I can do this with the following code:
Excel.Worksheet ws = Globals.ThisAddIn.Application.ActiveSheet;
Excel.Range range = ws.Range[ws.Cells[1,1], ws.Cells[4,4]];
ws.Names.Add("MyName", range);
How Can I do that in a add-in-express .COM AddIn? I tried so many ways, but i can't get the active Worksheet.
For Example, this doesn't work:
Excel.Worksheet ws = ExcelApp.ActiveSheet;
Thanks in advance,
Nicolas |
|
Andrei Smolin
Add-in Express team
Posts: 18829
Joined: 2006-05-11
|
|
Nicolas Fuerer
Posts: 6
Joined: 2014-06-26
|
Thanks a lot! Now it works!
With the range i have to do it the same way, i guess!?
object sheet = ExcelApp.ActiveSheet;
if (sheet is Excel.Worksheet) {
Excel.Worksheet wks = sheet as Excel.Worksheet;
object selection = ExcelApp.Selection;
if (selection is Excel.Range) {
Excel.Range range = selection as Excel.Range;
wks.Names.Add("MyName", range);
}
}
|
|
Andrei Smolin
Add-in Express team
Posts: 18829
Joined: 2006-05-11
|
I've missed releasing COM objects. Here' how this should look like (a raw sketch):
object sheet = ExcelApp.ActiveSheet;
if (sheet is Excel.Worksheet) {
Excel.Worksheet wks = sheet as Excel.Worksheet;
object selection = ExcelApp.Selection;
if (selection is Excel.Range) {
Excel.Range range = selection as Excel.Range;
Excel.Names names = wks.Names;
Excel.Name name = names.Add("MyName", range);
Marshal.ReleaseComObject(names); names = null;
Marshal.ReleaseComObject(name); name = null;
}
if (selection != null) Marshal.ReleaseComObject( selection); selection = null;
}
if (sheet != null) Marshal.ReleaseComObject(sheet); sheet = null;
Andrei Smolin
Add-in Express Team Leader |
|