Search code examples
c#vstoexcel-addins

Exception when accessing Globals.ThisAddIn.Application in VSTO AddIn


I am trying to create a MS Office VSTO AddIn using C#. The AddIn contains a Ribbon that i added via the Ribbon-Designer in VS19.

I left the ThisAddin.cs file untouched:

namespace MyAddIn
{
    public partial class ThisAddIn
    {

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {

        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}

In the ribbon I added a button and wrote some code to be executed when clicked:

namespace MyAddIn
{
    public partial class my_ribbon
    {
        private void my_ribbon_Load(object sender, RibbonUIEventArgs e)
        {

        }

        private void btn_myButton_Click(object sender, RibbonControlEventArgs e)
        {
            MessageBox.Show(Globals.ThisAddIn.Application.ThisWorkbook.FullName);
        }
    }
}

However, whenever I click on the button, C# throws me the following exception:

System.Runtime.InteropServices.COMException
  HResult=0x800A03EC
  Message=Ausnahme von HRESULT: 0x800A03EC
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

While debugging I saw, that Globals.ThisWorkbook.Application threw the error. I found out that 0x800A03EC is the error code for Name-Not-Found (according to this). But as I click the button once the file is opened, there should be an application object along with a full name.

I also took a look at this guide but that didn't help much because they also use Globals.ThisWorkbook.Application but successfully.

Do you have any advice on how to fix this? (Any more initialization code needed, etc?)


Solution

  • @Cindy Meister pointed me in the right direction:

    I am in fact writing an application-level add-in instead of a document-level customization and therefore don't have a ThisWorkbook. What I needed looking was Globals.ThisAddIn.Application.ActiveWorkbook (so the workbook instance where the click was invoked).

    Replacing ThisWorkbook with ActiveWorkbook did the trick.