Add excel vba code to button using c#

2020-07-17 07:20发布

I have a question about creating excel button and adding vba code function on it. I have created a button and module code but don't know how to make relation between them. Can anyone show me how?

my code for 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" });

and code for module:

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

2条回答
闹够了就滚
2楼-- · 2020-07-17 07:59

I have searched in Internet but didn't find anything usefull, so i cleared my mind and focused once more with c# help and I found an answer how to do it properly.

My Code:

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";
查看更多
地球回转人心会变
3楼-- · 2020-07-17 08:01

As far as I understand, you need the intermediate call to code/macro module from the button when you click on the button. So the code gets triggered and does what you want it to do.

In usual manner, for e.g.

  • we add a button in Excel Sheet
  • choose on_click event
  • add a code like call mySub

You need to do that within C#.

Please adjust for your module and control names. Here is a sample.

//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 It has pretty much what you need.

As per the subject on just invoking a sheet sub or module sub written in Excel from C#, you may use run macro method.

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

Reference:

查看更多
登录 后发表回答