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);
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:
As far as I understand, you need the intermediate
call
to code/macro module from thebutton
when youclick
on the button. So the code gets triggered and does what you want it to do.In usual manner, for e.g.
on_click
eventcall mySub
You need to do that within C#.
Please adjust for your module and control names. Here is a sample.
** 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.Reference: