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; } } } }
运行后:
标签:分发,excelApplication,Excel,System,互操作,targetExcelFile,var,using From: https://www.cnblogs.com/shiningleo007/p/17402564.html