使用c#添加excel vba代码到button

我有一个关于创buildExcelbutton和添加VBA代码function的问题。 我创build了一个button和模块代码,但不知道如何使它们之间的关系。 任何人都可以告诉我如何?

我的Button代码:

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); 

我在互联网search,但没有发现任何有用的,所以我清除了我的思想,并再次集中与C#的帮助,我find了一个答案如何正确做到这一点。

我的代码:

 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"; 

据我所知,当你click button时,你需要从button的中间call代码/macros模块。 所以代码被触发,做你想做的事情。

以通常的方式,例如,

  • 我们在Excel Sheet中添加一个button
  • selecton_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!"); } 

** 请尝试这个教程它几乎是你所需要的。

根据调用从C#编写的表单子或模块子的主题,您可以使用run macro方法。

 //instead of this.application, you call refer to the Excel app object this.Application.Run("yourMacroName",missing,missing........) 

参考: