Answer 1
As far as I can tell from
this KB article, the behavior you're seeing is unfortunately expected if you're trying to access the running instance of Excel with GetActiveObject or BindToMoniker before it loses focus for the first time. I'm not aware of any way to avoid this
when attaching to a running instance of Excel; perhaps someone else can chime in with better workarounds than displaying a message box.
A couple of follow-up questions:
Do you absolutely need to attach to a running instance of Excel? In other words, what is the workflow that users follow in your scenario: do they first run Excel, then they run your application, then they do something in your
application that requires you
to access the running instance of Excel to call into the add-in? The application
code you provided actually appears to programmatically
start Excel (Process.Start), which makes me wonder why you aren't just instantiating a Microsoft.Office.Interop.Excel.Application
object directly to start Excel, which is the simplest way to automate Excel in an early-bound fashion. For more details, see
http://blogs.msdn.com/b/andreww/archive/2008/11/30/starting-or-connecting-to-office-apps.aspx.
It isn't clear from your code why you have created an add-in at all. Does the AddInUtilities
class in your add-in implement some particular feature that you need to use from your application? If you just need to "communicate with Excel" from your application,
which I understand to mean that you need to call into the object model of Excel to perform some automation tasks, your simplest bet would be to stick to automating Excel from the PIAs. In other words, instantiate a Microsoft.Office.Interop.Excel.Application
object, use the Workbooks.Open
method to
open the
workbook you want to operate on or use Workbooks.Add to create a new workbook, etc.
Regarding your add-in object being null, depending on what version of the VSTO runtime your add-in targets, this might happen in some cases if you try to get the add-in object too soon after Excel starts. To work around this, you can try putting some sleeps
into your code until a valid add-in object is retrieved. For more information, see
http://blogs.msdn.com/b/andreww/archive/2008/08/13/comaddins-race-condition.aspx.
This posting is provided "AS IS" with no warranties, and confers no rights.