写在前面
在Excel文档的自动化处理流程中,有部分值需要通过已定义的宏来求解,所以延伸出了用C# 调用Excel中的宏代码的需求。
首先要从NuGet中引入Microsoft.Office.Interop.Excel 类库
using Excel = Microsoft.Office.Interop.Excel;
代码实现
/// <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;}}