工作表的控制方法不可用

时间:2015-04-17 09:26:02

标签: c# excel vsto add-in windows-controls

我在excel的程序设计加载项中遇到了一个奇怪的问题; 我想在excel中添加控件,我使用这段代码鼓舞人心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);
        }
    }
}

但工作表的控件方法不可用,我无法访问它,我添加了Microsoft.Office.Tools.Excel.v4.0.Utilities.dll程序集和以下语句

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

顺便说一句,我使用Office 2007和2013,所以我在DebugInfoExeName中将办公室版本更改为12。

1 个答案:

答案 0 :(得分: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);
    }
}