首页 > 解决方案 > 如何在excel VTO插件中重新创建按钮

问题描述

我有这段代码,当我按下功能区上的按钮时,它会被激活

Microsoft.Office.Tools.Excel.Worksheet vstoDocument = Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[1]);
Excel.Range selection = Globals.ThisAddIn.Application.Selection as Excel.Range;

 if (selection != null)
{
 Button button = new Button();
 button.Text = "THIS IS A BUTTON";
 vstoDocument.Controls.AddControl(button, selection, name);
 button.Click += new EventHandler(btn_Click);
// save the button state and name in custom properties 
 Excel.Worksheet sheet = Application.ActiveSheet as Excel.Worksheet;
 sheet.CustomProperties.Add("btnName" "btn_1");
 sheet.CustomProperties.Add("text","THIS IS A BUTTON");
 sheet.CustomProperties.Add("selection", selection);
}

//the click event
void btn_Click(object sender, EventArgs e)
{
 MessageBox.Show("I got Clicked");
}

所以当我按下ribbion上的按钮时这有效问题是当我保存excel并再次打开它时范围没有在我的启动代码中分配

 Excel.Application wb;
            wb = this.Application;

            if (wb.ActiveCell.Count > 0)
            {

                object docIndex = 1;
                Worksheet vstoDocument = Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[1]);
                foreach (Excel.CustomProperty prop in props)
                {
                    if (prop != null)
                    {
                        string pn = prop.Name;
                        if (pn.Contains("selection"))
                        {
                           
                            Excel.Range selection = prop.Value as Excel.Range;
                            if (selection != null)
                            {
                                Button button = new Button();
                               vstoDocument.Controls.AddControl(button, selection, "btn_1");//get an error here
                                button.Click += new EventHandler(btn_Click);
                                button.Text = "THIS IS A BUTTON";
                                button.TextAlign = ContentAlignment.MiddleCenter;
                            }
                        }
                    }
                }

我有一个错误说

System.OutOfMemoryException HResult=0x8007000E Message=没有足够的内存资源来完成此操作。(来自 HRESULT 的异常:0x8007000E (E_OUTOFMEMORY))来源 = StackTrace:

标签: c#excelvsto

解决方案


推荐阅读