通过Interop运行Excelmacros:如何将函数调用作为parameter passing?
我试图调用一个Excelmacros,作为它的第一个参数,本身调用一个函数。 我如何通过C#Excel互操作来做到这一点?
比方说,我在Excel中有这个子例程
Sub ValidateSheet(version As Integer, displayNoErrorsBox As Boolean)
我可以很容易地在Excel中调用这样的内容:
Call Validation.ValidateSheet(Data.GetVersion, False)
Data.GetVersion当然返回一个整数。
我如何通过互操作来调用? 传入的每个参数都是一个对象 – 我不确定是否可以将函数调用作为string传递。 这当然不起作用:
m_Application.Run("Validation.ValidateSheet", "Data.GetVersion", "False");
这可能吗? 我可以find关于这个主题的所有教程和post只是将string传递给macros。
刚刚使用了评论的build议,明确地调用了第一个macros。
所以,而不是尝试这个:
m_Application.Run("Validation.ValidateSheet", "Data.GetVersion", false);
我正在这样做:
string version = m_Application.Run("Data.GetVersion"); m_Application.Run("Validation.ValidateSheet", version, false);
尝试这个。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //~~> Define your Excel Objects Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkBook; //~~> Start Excel and open the workbook. xlWorkBook = xlApp.Workbooks.Open("E:\\Users\\Siddharth Rout\\Desktop\\book1.xlsm"); //~~> Run the macros by supplying the necessary arguments xlApp.Run("ShowMsg", "Hello from C# Client", "Demo to run Excel macros from C#"); //~~> Clean-up: Close the workbook xlWorkBook.Close(false); //~~> Quit the Excel Application xlApp.Quit(); //~~> Clean Up releaseObject(xlApp); releaseObject(xlWorkBook); } //~~> Release the objects private void releaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; } finally { GC.Collect(); } } } }