在代码窗口中,将以下代码private void button1_Click(object sender, System.EventArgs e)
{
}
替换为: private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application oExcel;
Excel.Workbook oBook;
VBIDE.VBComponent oModule;
Office.CommandBar oCommandBar;
Office.CommandBarButton oCommandBarButton;
String sCode;
Object oMissing = System.Reflection.Missing.Value;
// Create an instance of Excel.
oExcel = new Excel.Application();
// Add a workbook.
oBook = oExcel.Workbooks.Add(oMissing);
// Create a new VBA code module.
oModule = oBook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
sCode =
"sub VBAMacro()\r\n" +
" msgbox \"VBA Macro called\"\r\n" +
"end sub";
// Add the VBA macro to the new code module.
oModule.CodeModule.AddFromString(sCode);
try
{
// Create a new toolbar and show it to the user.
oCommandBar = oExcel.CommandBars.Add("VBAMacroCommandBar",oMissing, oMissing,\);
oCommandBar.Visible = true;
// Create a new button on the toolbar.
oCommandBarButton = (Office.CommandBarButton) oCommandBar.Controls.Add(
Office.MsoControlType.msoControlButton,
oMissing, oMissing, oMissing, oMissing);
// Assign a macro to the button.
oCommandBarButton.OnAction = "VBAMacro";
// Set the caption of the button.
oCommandBarButton.Caption = "Call VBAMacro";
// Set the icon on the button to a picture.
oCommandBarButton.FaceId = 2151;
}
catch(Exception eCBError) {
MessageBox.Show("VBAMacroCommandBar already exists.","Error");
}
// Make Excel visible to the user.
oExcel.Visible = true;
// Set the UserControl property so Excel won't shut down.
oExcel.UserControl = true;
// Release the variables.
oCommandBarButton = null;
oCommandBar = null;
oModule = null;
oBook = null;
oExcel = null;
// Collect garbage.
GC.Collect();
}
|