| 1. |
啟動 Microsoft Visual Studio .NET。 |
| 2. |
在檔案菜單上,單擊建立,然後單擊項目。從 Visual C# 項目類型中選擇 Windows 應用程式。預設情況下會建立 Form1。 |
| 3. |
添加對 Microsoft Excel 物件程式庫和 Microsoft Visual Basic for Applications 擴充庫的引用。為此,請按照下列步驟操作:
| a. |
在項目菜單上,單擊添加引用。 |
| b. |
在 COM 選項卡上,找到 Microsoft Excel 物件程式庫,然後單擊選擇。然後找到 Microsoft Visual Basic for Applications 擴充庫並單擊選擇。 注意:Microsoft Office 2003 包含主 Interop 程式集 (PIA)。Microsoft Office XP 不包含 PIA,但您可以下載 PIA。 有關 Office XP PIA 的其他資訊,請單擊下面的文章編號,以查看 Microsoft 知識庫中相應的文章: 328912 (http://support.microsoft.com/kb/328912/) INFO: Microsoft Office XP PIA 可供下載 |
| c. |
在添加引用對話方塊中單擊確定以接受您的選擇。 |
|
| 4. |
在視圖菜單上,選擇工具箱以顯示工具箱,然後向 Form1 添加一個按鈕。 |
| 5. |
雙擊 Button1。代碼視窗開啟並顯示 Button1 的 Click 事件。將以下程式碼添加到代碼視窗頂部的 using 語句中:using Office = Microsoft.Office.Core; using VBIDE = Microsoft.Vbe.Interop; using Excel = Microsoft.Office.Interop.Excel;
|
| 6. |
在代碼視窗中,將以下代碼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(); }
|
| 7. |
按 F5 鍵產生並運行該程式。 |
| 8. |
單擊 Button1 啟動 Microsoft Excel,插入 Visual Basic for Applications (VBA) 代碼,然後添加一個新的 CommandBar。單擊 CommandBar 上的按鈕以運行 VBA 宏。 |
此文章為轉載,如出現
關於“ 不信任到Visual Basic Project 的程式串連”問題
解決方案如下:
開啟Excel-》工具-》宏-》安全性-》可靠發行商,選中“信任對於Visiual Basic 項目的訪問”,按確定即可。