My project requires adding a button to the Excel sheet, similar to the simplified code below. But once the sheet is closed and opened again, the button cannot be clicked. How can I save the status of this button so that it can be retained every time I open this spreadsheet?
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Tools.Ribbon;
using Tools = Microsoft.Office.Tools.Excel;
using System;
using System.Windows.Forms;
namespace ExcelAddIn1
{
public partial class Ribbon
{
private void Ribbon_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Tools.Worksheet worksheet = Globals.Factory.GetVstoObject(
Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[1]);
string buttonName = "MyButton";
RibbonButton clickedButton = sender as RibbonButton;
if (clickedButton != null)
{
MessageBox.Show("Button added");
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();
button.Text = "Click Me";
button.Click += Button_Click;
var addedButton = worksheet.Controls.AddControl(button, selection, buttonName);
addedButton.AutoLoad = true;
}
}
else
{
worksheet.Controls.Remove(buttonName);
}
}
private void Button_Click(object sender, EventArgs e)
{
MessageBox.Show("Button was clicked!");
}
}
}
Due to the large number of buttons that need to be added to multiple sheets in my project, I tried to add a WorkbookBeforeSave event, but I don’t know how to traverse my buttons, save them for status, and reload their status the next time I open them.
How to solve it? Thanks.
user24877793 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.