如何通过Interop将函数调用作为参数传递给Excel宏?

问题描述 投票:1回答:2

我正在尝试调用一个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");
c# excel vba excel-vba office-interop
2个回答
1
投票

刚刚使用了评论中的建议并明确调用了第一个宏。

所以,而不是尝试这个:

m_Application.Run("Validation.ValidateSheet", "Data.GetVersion", false);

我这样做:

string version = m_Application.Run("Data.GetVersion");
m_Application.Run("Validation.ValidateSheet", version, false);

-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();
            }
        }
    }
}

https://social.msdn.microsoft.com/Forums/Lync/en-US/2e33b8e5-c9fd-42a1-8d67-3d61d2cedc1c/how-to-call-excel-macros-programmatically-in-c?forum=exceldev

© www.soinside.com 2019 - 2024. All rights reserved.