0

I'm having trouble connecting my Workbook_SheetChange Event Handler to an active workbook. I've tried several methods to no avail, it just keeps saying my workbook or instance of Excel (xlApp) is null and throws the exception.

Here's the code:

private void createProject_Click(object sender, RibbonControlEventArgs e) 
    {
        Excel.Application xlApp;

        xlApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");

        exwb = (Excel.Workbook)xlApp.ActiveWorkbook;

        MessageBox.Show(exwb.Name);
        EventDel_CellsChange = new Excel.WorkbookEvents_SheetChangeEventHandler(narrator.Workbook_SheetChange);
        xlApp.ActiveWorkbook.SheetChange += EventDel_CellsChange;
    }

The problem is the last line and please note I've substituted xlApp.ActiveWorkbook for exwb multiple times

Drew2127
  • 1
  • 3

1 Answers1

0

Probably something went wrong in creating the Excel application. Marshal.GetActiveObject isn't the easiest way to create a Excel.Application instance. Try this instead:

xlApp = new Excel.Application();
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • I apologize for not clarifying, I want my code (event handler) to be activated and tied to the workbook_sheetchange event of the active workbook, once my ribbon button is clicked. So in this case I'm trying to grab the active instance of excel and it's active workbook. – Drew2127 Jan 22 '15 at 18:56
  • Why are you doing all that marshalling? Don't you use VSTO? – Patrick Hofman Jan 22 '15 at 18:57
  • "it just keeps saying my workbook or instance of Excel (xlApp) is null " sounds like a problem with initialization though. – Patrick Hofman Jan 22 '15 at 18:58
  • sorry I'm new to this, what would be my options with VSTO? are there better ways to get active instances of excel? and yes it's definitely initialization because this works fine if I create a new instance, add a workbook, and add a sheet. – Drew2127 Jan 22 '15 at 19:13
  • You own the instance when running VSTO. No need to marshal yourself. Really, it makes your life a lot easier. – Patrick Hofman Jan 22 '15 at 19:14
  • so i create a project as a vsto add-in? and I shouldn't have to worry about this? – Drew2127 Jan 22 '15 at 19:53
  • No. Creating instances of the application and so are done by vsto. – Patrick Hofman Jan 22 '15 at 19:54