1

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.

4

2 回答 2

1

使用正确的命名空间解决了我的类似问题:

using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Tools.Excel;
于 2022-01-11T04:46:59.783 回答
0

您需要使用GetVstoObject方法在工作簿中获取代表工作表的宿主项,然后将Button 控件添加到当前选定的单元格中。

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);
    }
}
于 2015-04-17T14:33:40.063 回答