我有一个现有宏函数的问题,所以我要做的是将宏传递给excel我的意思是将函数(Ex:a())添加到excel,然后运行函数(“a() “)补充说。
注意:我有excel的路径,我必须添加宏。请清楚答案。
怎么做?
提前致谢。
答案 0 :(得分:7)
添加对程序集的引用 - >扩展程序 - > Microsoft.Office.Interop.Excel和Microsoft.VBE.Interop
using System;
using System.Diagnostics;
using System.Windows.Forms;
using Microsoft.Vbe.Interop;
using ExcelInterop = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication1
{
public partial class AddExcelMacro : Form
{
public AddExcelMacro()
{
InitializeComponent();
AddMacro();
}
public void AddMacro()
{
try
{
// open excel file
const string excelFile = @"c:\temp\VBA\test.xlsm";
var excelApplication = new ExcelInterop.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;
}
}
}
}