使用c将excel vba代码添加到按钮#
我有一个关于创建excel按钮并在其上添加vba代码功能的问题。我创建了一个按钮和模块代码,但不知道如何建立它们之间的关系。任何人都可以告诉我如何?使用c将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, 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);
我已经搜索在互联网,但没有发现任何有用的,所以我清除我的脑海里,并用C#的帮助再次集中,我找到了答案如何正确地做到这一点。
我的代码:
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";
据我了解,你所需要的中间call
代码从button
当你click
/宏模块在按钮上。所以代码被触发,并做你想做的事情。
以通常的方式,例如,
- 我们在Excel工作表
- 添加一个按钮选择
on_click
事件 - 添加像
call mySub
你需要做的是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!");
}
** PLEASE TRY THIS TUTORIAL OUT它几乎你所需要的。
根据调用从C#在Excel中编写的sheet子或模块子的主题,您可以使用run macro
方法。
//instead of this.application, you call refer to the Excel app object
this.Application.Run("yourMacroName",missing,missing........)
类似于'MSForms.CommandButton cmdButton = sheetBtn.Object; cmdButton.Click + =新MSForms.CommandButtonEvents_ClickEventHandler(cmdButton_Click);'然后'空隙cmdButton_Click() { }'?但我应该在cmdbutton_click中写什么? –
没有与sheetBtn.Click功能 –
你有没有在Excel中使用已经创建的按钮的自由?那个按钮事件在Excel中已经有了'call subMain'? – bonCodigo
+1了有趣的问题。也许你以后可以用最终答案来更新你的问题,以使你和我这样的人受益。 :-) – bonCodigo