gpt4 book ai didi

c# excel在excel工作表上创建一个按钮

转载 作者:行者123 更新时间:2023-12-04 22:04:34 27 4
gpt4 key购买 nike

我正在尝试在 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 属性时应该包含哪些引用?

最佳答案

据我所知,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

关于c# excel在excel工作表上创建一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26710202/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com