我正在尝试调用一个Excel宏,它作为第一个参数调用一个函数。
假设我在Excel中有这个子程序
Sub ValidateSheet(version As Integer, displayNoErrorsBox As Boolean)
我可以像这样在Excel中调用:
Call Validation.ValidateSheet(Data.GetVersion, False)
Data.GetVersion
当然会返回一个整数。
如何通过C#Excel interop执行此操作?
传递的每个参数都是一个对象。我可以找到所有教程和帖子传递字符串。是否可以将函数调用作为字符串传递?
这不起作用:
m_Application.Run("Validation.ValidateSheet", "Data.GetVersion", "False");
答案 0 :(得分:-1)
试试这个。
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();
}
}
}
}