有翅膀Excel-可重新分发的主互操作程序集

using Microsoft.Vbe.Interop;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace DoVBAMacro
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            AddMacro();
        }

        public void AddMacro()
        {
            try
            {
                // open excel file 
                const string excelFile = @"C:\Users\Desktop\vba\test1.xlsm";
                var excelApplication = new Excel.Application { Visible = true };
                var targetExcelFile = excelApplication.Workbooks.Open(excelFile);

                // add standart module to file
                var newStandardModule = targetExcelFile.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
                var codeModule = newStandardModule.CodeModule;

                // add vba code to module
                var lineNum = codeModule.CountOfLines + 1;
                var macroName = "Button1_Click";
                var codeText = "Public Sub " + macroName + "()" + "\r\n";
                codeText += "  MsgBox \"Hi from Excel\"" + "\r\n";
                codeText += "End Sub";

                codeModule.InsertLines(lineNum, codeText);
                targetExcelFile.Save();

                // run the macro
                var macro = string.Format("{0}!{1}.{2}", targetExcelFile.Name, newStandardModule.Name, macroName);
                excelApplication.Run(macro);

                excelApplication.Quit();

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
    }
}

运行后:

 

posted @ 2023-05-15 17:24  有翅膀的大象  阅读(19)  评论(0编辑  收藏  举报