C#给指定doc文件写入宏

     private void InsertMacro()
        {
            Word.Application oWord;
            Word.Document oDoc;
            VBIDE.VBComponent oModule;
            Office.CommandBar oCommandBar;
            Office.CommandBarButton oCommandBarButton;
            String sCode;
            Object oMissing = System.Reflection.Missing.Value;

            oWord = new Word.Application();
            oDoc = oWord.Documents.Open(fileName);
            //oDoc = oWord.Documents.Add(oMissing);
            try
            {
                // Create a new VBA code module.
                oModule = oDoc.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
                sCode =
                "sub AutoOpen()\r\n" +
                "Application.DisplayAlerts = False \r\n" +
                "   msgbox \"VBA Macro called\"\r\n" +
                "Application.DisplayAlerts = True \r\n" +
                "end sub";
                // Add the VBA macro to the new code module.
                oModule.CodeModule.AddFromString(sCode);
            }
            catch (Exception e)
            {
                if (e.ToString().Contains("不被信任"))
                    MessageBox.Show("到 Visual Basic Project 的程序访问不被信任", "Error");
                return;
            }
            try
            {
                // Create a new toolbar and show it to the user.
                oCommandBar = oWord.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 e)
            {
                MessageBox.Show("VBA宏命令已经存在.", "Error");
            }

            oWord.Documents.Save();
            //oWord.Visible = true;

            oCommandBarButton = null;
            oCommandBar = null;
            oModule = null;
            oDoc = null;
            oWord = null;
            GC.Collect();
        }

 

posted @ 2017-04-10 10:12  Cherry的冬天  阅读(897)  评论(2编辑  收藏  举报