1

I've seen similar questions asked, but none that I've found have resolved into a solution for my specific situation.

I have an Excel 2007 COM add-in in Visual Studio 2010, written in C#. When I load the activeworkbook into a workbook object in the ribbon code, it works fine. When I do it in a windows form, it returns null from the activeworkbook every time.

The following are my using statements and the snippet of code where the error keeps happening.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Office = Microsoft.Office.Core;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Drawing;

---------------------------------------------------

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

Excel.Workbook xlWkbk = (Excel.Workbook)xlApp.ActiveWorkbook;
Excel.Worksheet xlWksht = (Excel.Worksheet)xlWkbk.ActiveSheet;

Any help would be greatly appreciated!

Daniel
  • 13
  • 3
  • 2
    You never opened / created a new workbook, so you created an Excel shell with nothing open, I think.... – John Bustos Sep 02 '14 at 20:25
  • John, thanks for the reply! So, I'm not trying to create or open any workbook. I just want the activeworkbook. – Daniel Sep 02 '14 at 21:47

1 Answers1

0

The code itself works as long and only if your Task Manager has 1 EXCEL.EXE process listed.

I suspect you are testing things and not properly disposing of EXCEL.EXE or have no error handling therefore you Marshal into the wrong EXCEL.EXE process.

Add an error handler and dispose properly of Excel by following THIS ANSWER.

Community
  • 1
  • 1
  • 1
    Fantastic! I made sure there was only one process running, and it worked. I'll check this out to automate process management. – Daniel Sep 04 '14 at 22:11