【问题标题】:c# excel create a button on excel worksheetc# excel在excel工作表上创建一个按钮
【发布时间】:2021-01-08 09:37:30
【问题描述】:

我正在尝试在 Excel 工作表上添加一个按钮。 根据来自互联网的示例,我正在尝试执行以下代码。

  using Excel = Microsoft.Office.Interop.Excel;
  using VBIDE = Microsoft.Vbe.Interop;


 private static void excelAddButtonWithVBA()
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlBook = xlApp.Workbooks.Open(@"PATH_TO_EXCEL_FILE");
Excel.Worksheet wrkSheet = xlBook.Worksheets[1];
Excel.Range range;

try
{
    //set range for insert cell
    range = wrkSheet.get_Range("A1:A1");

    //insert the dropdown into the cell
    Excel.Buttons xlButtons = wrkSheet.Buttons();
    Excel.Button xlButton = xlButtons.Add((double)range.Left, (double)range.Top, (double)range.Width, (double)range.Height);

    //set the name of the new button
    xlButton.Name = "btnDoSomething";
    xlButton.Text = "Click me!";
    xlButton.OnAction = "btnDoSomething_Click";

    buttonMacro(xlButton.Name, xlApp, xlBook, wrkSheet);
}
catch (Exception ex)
{
    Debug.WriteLine(ex.Message);
}
xlApp.Visible = true;

}

但它一直说“Excel不包含按钮”

使用 Button 属性应该包含哪些参考?

【问题讨论】:

  • wrkSheet.Buttons();你可以试试 wrkSheet.Buttons; ?
  • 工作表没有按钮功能。要使用工作表按钮,我需要包含哪些参考?

标签: c# excel excel-interop


【解决方案1】:

据我所知,Excel.Buttons 和 Excel.Button 不存在。相反,建议正确的参考是 Microsoft.Office.Tools.Excel.Controls.Button(不是您使用的 Microsoft.Office.Interop.Excel)。此示例来自以下来源

    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlBook = xlApp.Workbooks.Open(@"PATH_TO_EXCEL_FILE");
    Excel.Worksheet worksheet = xlBook.Worksheets[1];

    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, "Button");
    }

来源:在应用程序级项目的运行时向工作表添加控件http://msdn.microsoft.com/en-us/library/cc442817.aspx

【讨论】:

  • 感谢您的回复。我包含了 Microsoft.Office.Tools.Excel.v4.0.Utilities.dll,但我找不到 Microsoft.Office.Tools.Excel.Controls。我想知道我错过了什么。
  • 我找到了!对不起,我只是瞎了。谢谢!
  • 哦。我找不到 worksheet.Controls... 我需要包含哪些参考资料?我将工作表声明为 Microsoft.Office.Interop.Excel.Worksheet。
  • 抱歉,我不太清楚 - 工作表应该是您的活动工作表的一个实例。例如,您的示例中的 E.G:Excel.Worksheet worksheet = xlBook.Worksheets[1]; 我也更新了答案
  • 在哪里可以获得 Microsoft.Office.Tools.Excel.Controls.Button?
【解决方案2】:

使用 Lesley.Oakey 的方法需要您在 Microsoft.Tools.Office.Excel 中使用VSTO extension methods

如果您不使用它们,那么您将无法访问 Worksheet.Controls 属性。

最好只使用 Worksheet.Shapes 容器并添加一个新形状。这里有一篇很棒的帖子:

Add excel vba code to button using c#

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    相关资源
    最近更新 更多