c# - xlApp.ActiveWorkbook returns null -
i have 2010 excel ribbon add-in. when press button writes lines of info excel app. in order write info need active worksheet. , in order active worksheet need activeworkbook. can xlapp fine
xlapp = (excel.application)system.runtime.interopservices.marshal.getactiveobject("excel.application");
and retrieves xlapp fine whenever seek active workbook returns null. no matter what. unless restart computer. works, first time. below whole block of code in context. i'm wondering how prepare xlapp.activeworkbook beingness null. can active worksheet. , write info active worksheet.
public void senddata() { excel.application xlapp = null; excel.workbook xlworkbook = null; excel.workbooks xlworkbooks = null; excel.worksheet xlworksheet = null; object misvalue = system.reflection.missing.value; seek { xlapp = new excel.application(); //xlworkbooks = xlapp.workbooks; //xlworkbook = xlworkbooks.add(properties.settings.default.filetosend); //xlworksheet = xlworkbook.sheets[1]; xlapp = (excel.application)system.runtime.interopservices.marshal.getactiveobject("excel.application"); xlworkbook = (excel.workbook)xlapp.activeworkbook; xlworksheet = (excel.worksheet)xlworkbook.activesheet; } grab (exception ex) { // handle error... } { if (xlworksheet != null) marshal.releasecomobject(xlworksheet); if (xlworkbook != null) marshal.releasecomobject(xlworkbook); if (xlworkbooks != null) marshal.releasecomobject(xlworkbooks); if (xlapp != null) marshal.releasecomobject(xlapp); }
thanks in advance!
you're getting hold of wrong excel instance phone call getactiveobject
. utilize application reference passed com add-in's onconnection
(or ribbon code bootstrapped).
if you're using excel-dna framework create managed excel add-in, hold of right application object phone call exceldnautil.application
.
c# excel interop ribbon
No comments:
Post a Comment