C# 使用c将excel vba代码添加到按钮#
我有一个关于创建excel按钮和添加vba代码函数的问题。我已经创建了一个按钮和模块代码,但不知道如何建立它们之间的关系。有人能告诉我怎么做吗 我的按钮代码:C# 使用c将excel vba代码添加到按钮#,c#,excel,button,vba,C#,Excel,Button,Vba,我有一个关于创建excel按钮和添加vba代码函数的问题。我已经创建了一个按钮和模块代码,但不知道如何建立它们之间的关系。有人能告诉我怎么做吗 我的按钮代码: Excel.Shape btn = xlWorkSheet5.Shapes.AddOLEObject("Forms.CommandButton.1", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 300, 10,
Excel.Shape btn = xlWorkSheet5.Shapes.AddOLEObject("Forms.CommandButton.1", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 300, 10, 150, 22);
Excel.OLEObject sheetBtn = (Excel.OLEObject)xlWorkSheet5.OLEObjects(btn.Name);
sheetBtn.Object.GetType().InvokeMember("Caption", System.Reflection.BindingFlags.SetProperty, null, sheetBtn.Object, new object[] { "Calculate Bus Load" });
模块的名称和代码:
String sCode = "Sub main()\r\n" +
" MsgBox \"Hello world\"\r\n" +
"end Sub";
VBA.VBComponent oModule = xlWorkBook.VBProject.VBComponents.Add(VBA.vbext_ComponentType.vbext_ct_StdModule);
oModule.Name = "Module1";
oModule.CodeModule.AddFromString(sCode);
xlWorkBook.VBProject.VBComponents.Item(1).CodeModule.AddFromString(sCode);
据我所知,当您单击按钮上的
时,您需要从按钮
调用中间到编码/宏模块。因此,代码会被触发,并执行您希望它执行的操作
以通常的方式,例如
- 我们在Excel工作表中添加了一个按钮
- 在单击事件时选择
- 添加一个代码,如
callmysub
你需要在C#内完成这项工作
请根据您的模块和控件名称进行调整。这是一个样本
//Within your above code add,
sheetBtn.Click += new MSForms.CommandButtonEvents_ClickEventHandler(sheetBtn_Click);
}
//button click event triggers
void sheetBtn_Click()
{
call subMain
// try a test using : MessageBox.Show("button test!");
}
**它几乎满足了你的需要
根据从C#调用Excel中编写的工作表子系统或模块子系统的主题,您可以使用run macro
方法
//instead of this.application, you call refer to the Excel app object
this.Application.Run("yourMacroName",missing,missing........)
我在互联网上搜索过,但没有找到任何有用的东西,所以我在c#help的帮助下清理了思路,再次集中精力,找到了如何正确操作的答案
我的代码:
String updateBT "...// macro code for button";
VBA.VBComponent oModule1 = xlWorkBook.VBProject.VBComponents.Add(VBA.vbext_ComponentType.vbext_ct_StdModule);
oModule1.Name = "Update";
oModule1.CodeModule.AddFromString(updateBT);
Excel.Shape btn2 = xlWorkSheet1.Shapes.AddFormControl(Excel.XlFormControl.xlButtonControl, 150, 5, 150, 22);
btn2.Name = "Update";
btn2.OnAction = "... // name of your macro code";
btn2.OLEFormat.Object.Caption = "... // Button name";
类似于'MSForms.CommandButton cmdButton=sheetBtn.Object;cmdButton.Click+=新建MSForms.CommandButtonEvents\u ClickEventHandler(cmdButton\u Click);`然后“void cmdButton\u Click(){}”?但是我应该在cmdbutton\u click中写什么呢?您有权在Excel中使用已经创建的按钮吗?按钮事件在Excel中已经有了调用子模块
?嗯,我不这么认为,我如何激活它?有趣的问题是+1。也许您可以稍后用最终答案更新您的问题,以使像您和我这样的人受益。:-)