Search code examples
c#excelvstoadd-inwindows-controls

control method of worksheet is not available


I've encountered an odd problem in proggramming add-in for excel; i wanna add controls in excel, i used this code inspiring https://msdn.microsoft.com/en-us/library/cc442817.aspx

private void button_Click(object sender, RibbonControlEventArgs e)
{
    var worksheet = (Worksheet)Globals.ThisAddIn.Application.ActiveSheet;
    {
        const string buttonName = "MyButton";

        if (((RibbonCheckBox)sender).Checked)
        {
            var selection = Globals.ThisAddIn.Application.Selection as Range;
            if (selection != null)
            {
                var button =
                    new Microsoft.Office.Tools.Excel.Controls.Button();
                worksheet.Controls.AddControl(button, selection, buttonName);
            }
        }
        else
        {
            worksheet.Controls.Remove(buttonName);
        }
    }
}

but controls method of worksheet is not available and i can't access it, i added Microsoft.Office.Tools.Excel.v4.0.Utilities.dll assembly and following statements

using Microsoft.Office.Interop.Excel; 
using Microsoft.Office.Tools.Ribbon;
using Office = Microsoft.Office.Core;

by the way I'm using office 2007 and vs 2013 so i changed office version to 12 in DebugInfoExeName.


Solution

  • You need to use the GetVstoObject method to get a host item that represents the worksheet in the workbook, and then adds a Button control to the currently selected cell.

    private void Button_Click(object sender, RibbonControlEventArgs e)
    {
        Worksheet worksheet = Globals.Factory.GetVstoObject(
           Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[1]);
        string buttonName = "MyButton";
    
        if (((RibbonCheckBox)sender).Checked)
        {
            Excel.Range selection = Globals.ThisAddIn.Application.Selection as Excel.Range;
            if (selection != null)
            {
                Microsoft.Office.Tools.Excel.Controls.Button button =
                   new Microsoft.Office.Tools.Excel.Controls.Button();
                worksheet.Controls.AddControl(button, selection, buttonName);
            }
        }
        else
        {
            worksheet.Controls.Remove(buttonName);
        }
    }