C#调用Excel Vba
c#程序调用Excel程序,可以让excel显示,也可以让excel不显示,但经过多次测试,如果excel不显示执行vba,则之前必须打开过一次,否则就会报错
这是需要引用的dll
using Microsoft.Office.Interop.Excel
using Microsoft.Office.Core
using Excel = Microsoft.Office.Interop.Excel; using Microsoft.Office.Core; using System.IO;
//下面这两个函数闭着眼睛直接抄
string xadd = @"C:\Users\Administrator\Desktop\set.xlsm"; //记录excel地址文件
/// <summary>
/// 执行Excel中的宏
/// </summary>
/// <param name="excelFilePath">Excel文件路径</param>
/// <param name="macroName">宏名称</param>
/// <param name="parameters">宏参数组</param>
/// <param name="rtnValue">宏返回值</param>
/// <param name="isShowExcel">执行时是否显示Excel</param>
public void RunExcelMacro(string excelFilePath, string macroName, object[] parameters, out object rtnValue, bool isShowExcel) { try { #region 检查入参 // 检查文件是否存在 if (!File.Exists(excelFilePath)) { throw new System.Exception(excelFilePath + " 文件不存在"); } // 检查是否输入宏名称 if (string.IsNullOrEmpty(macroName)) { throw new System.Exception("请输入宏的名称"); } #endregion #region 调用宏处理 // 准备打开Excel文件时的缺省参数对象 object oMissing = System.Reflection.Missing.Value; // 根据参数组是否为空,准备参数组对象 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]; } } // 创建Excel对象示例 Excel.ApplicationClass oExcel = new Excel.ApplicationClass(); // 判断是否要求执行时Excel可见 if (isShowExcel) { // 使创建的对象可见 oExcel.Visible = true; } else { oExcel.Visible = false; } // 创建Workbooks对象 Excel.Workbooks oBooks = oExcel.Workbooks; // 创建Workbook对象 Excel._Workbook oBook = null; // 打开指定的Excel文件 oBook = oBooks.Open( excelFilePath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing ); // 执行Excel中的宏 rtnValue = this.RunMacro(oExcel, paraObjects); // 保存更改 oBook.Save(); // 退出Workbook oBook.Close(false, oMissing, oMissing); #endregion #region 释放对象 // 释放Workbook对象 System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook); oBook = null; // 释放Workbooks对象 System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks); oBooks = null; // 关闭Excel oExcel.Quit(); // 释放Excel对象 System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel); oExcel = null; // 调用垃圾回收 GC.Collect(); #endregion } catch (Exception ex) { throw ex; } } /// <summary> /// 执行宏 /// </summary> /// <param name="oApp">Excel对象</param> /// <param name="oRunArgs">参数(第一个参数为指定宏名称,后面为指定宏的参数值)</param> /// <returns>宏返回值</returns> private object RunMacro(object oApp, object[] oRunArgs) { try { // 声明一个返回对象 object objRtn; // 反射方式执行宏 objRtn = oApp.GetType().InvokeMember( "Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, oApp, oRunArgs ); // 返回值 return objRtn; } catch (Exception ex) { if (ex.InnerException.Message.ToString().Length > 0) { throw ex.InnerException; } else { throw ex; } } }
c#执行
private void button1_Click(object sender, EventArgs e) { try { // 返回对象 object objRtn = new object(); //执行指定Excel中的宏,执行时显示Excel RunExcelMacro( xadd, "getTime", new Object[] { }, out objRtn, true ); // 执行指定Excel中的宏,执行时不显示Excel RunExcelMacro( xadd, "getTime2", new Object[] { "现在时刻" }, out objRtn, false ); //执行指定Excel中的宏,执行时显示Excel,有返回值 RunExcelMacro( xadd, "getTime3", new Object[] { "现在时刻" }, out objRtn, false ); MessageBox.Show((string)objRtn); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } }
vba函数类型
Sub getTime() Sheet1.Cells(1, 1) = Now End Sub Sub getTime2(title As String) Sheet1.Cells(2, 1) = title & " : " & Now End Sub Function getTime3(title As String) As String getTime3 = title & " : " & Now End Function
注:
期间有个无法嵌入互操作类型“Microsoft.Office.Interop.Excel.ApplicationClass”。请改用适用的接口
解决方法:选中引用的DLL:Microsoft.Office.Interop.Excel;右键属性,找到"嵌入互操作类型",将true改为false,就可以了