ExcelInterop.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 Microsoft.Office.Interop.Excel.Application(); var oExcel = new ExcelInterop.Application { Visible = true }; // 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();
Exception from HRESULT: 0x800AC472 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x800AC472
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)