using System; using Excel = Microsoft.Office.Interop.Excel; namespace WindowsFormsApplication1 { /// <summary> /// 执行Excel VBA宏帮助类 /// </summary> public class ExcelMacroHelper { /// <summary> /// 执行Excel中的宏 /// </summary> /// <param name="excelFilePath">Excel文件路径</param> /// <param name="macroName">宏名称</param> /// <param name="parameters">宏参数组</param> /// <param name="rtnValue">宏返回值</param> public void RunExcelMacro(Excel.Application app, string macroName, object[] parameters, out object rtnValue) { // 根据参数组是否为空,准备参数组对象 object[] paraObjects; if (parameters == null) paraObjects = new object[] { macroName }; else { int paraLength = parameters.Length; paraObjects = new object[paraLength + 1]; paraObjects[0] = macroName; for (int i = 0; i < paraLength; i++) paraObjects[i + 1] = parameters[i]; } rtnValue = this.RunMacro(app, paraObjects); } /// <summary> /// 执行宏 /// </summary> /// <param name="oApp">Excel对象</param> /// <param name="oRunArgs">参数(第一个参数为指定宏名称,后面为指定宏的参数值)</param> /// <returns>宏返回值</returns> private object RunMacro(object app, object[] oRunArgs) { object objRtn; // 声明一个返回对象 // 反射方式执行宏 objRtn = app.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, app, oRunArgs); return objRtn; } } }
使用方法
app = new Microsoft.Office.Interop.Excel.Application(); app.Visible = true; string filePath = @"F: est.xlsm"; Workbook wb = app.Workbooks.Open(filePath); object objRtn = new object(); // 执行指定Excel中的宏,执行时显示Excel ExcelMacroHelper excelMacroHelper = new ExcelMacroHelper(); excelMacroHelper.RunExcelMacro(app,"hong",new Object[] { "现在时刻" },out objRtn); MessageBox.Show(objRtn.ToString());
在Excel中新增“模块”
Function hong(title As String) Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Sheet1") ws.Cells(1, 1).Value = title & ",123" hong = title & ",123" End Function