简体   繁体   English

工作表的控制方法不可用

[英]control method of worksheet is not available

I've encountered an odd problem in proggramming add-in for excel;我在为 excel 编程插件时遇到了一个奇怪的问题; i wanna add controls in excel, i used this code inspiring https://msdn.microsoft.com/en-us/library/cc442817.aspx我想在 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);
        }
    }
}

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但工作表的控制方法不可用,我无法访问它,我添加了 Microsoft.Office.Tools.Excel.v4.0.Utilities.dll 程序集和以下语句

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.顺便说一句,我使用的是 office 2007 和 vs 2013,所以我在 DebugInfoExeName 中将 office 版本更改为 12。

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. 您需要使用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);
    }
}

Using correct namespaces solved my problem which is similar:使用正确的命名空间解决了我的类似问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM