繁体   English   中英

建立与现有Excel应用程序的连接并运行Excel宏C#

[英]Establish Connection to existing Excel Application and Run an Excel macro C#

所有,

抱歉,如果这是一个非常基本的问题,并且已经被问过,我主要使用VBA / JAVA编写。 但是,我正在从事的项目需要C#脚本。 它执行3个简单步骤:

  1. 定位已打开的Excel工作簿。 文件路径:

    \\ Csdatg04 \\ psproject \\ Robot \\ Peoplesoft到LV \\主文件-不要使用\\向LV Template.xlsm的交易

  2. 用早先在自动化中已检索到的三个变量填充单元格A1,A2和A3。

  3. 运行存储在上述文件路径中的宏宏名称“ ControlMacroACT”

我开发的代码在下面,但是在上面确定的每个阶段中,我都遇到错误(可能是基本错误)。

错误1:这行代码是要打开一个工作簿,我希望这是针对已处于活动状态的工作簿的。

错误2:找不到工作表

public void RunActualsMacro(string Filepath, string Period, String FiscalYear)
    {
        //~~> Define your Excel Objects
        Excel.Application xlApp = new Excel.Application();

        Excel.Workbook xlWorkBook;

        //~~> Start Excel and open the workbook.
        //Error 1
        xlWorkBook = xlApp.Workbooks.Open("\\Csdatg04\\psproject\\Robot\\Peoplesoft To LV\\Master Files - Do not use\\Transactions into LV Template.xlsm");

        // Populat Cells A1,A2,A3 with string variables
        // Error 2 Worksheet not found
        worksheet.Rows.Cells[1, 1] = Filepath;
        worksheet.Rows.Cells[2, 1] = Period;
        worksheet.Rows.Cells[3, 1] = FiscalYear;


        //~~> Run the macro ControlMacroAct
        xlApp.Run("ControlMacroACT");

        //~~> Clean-up: Close the workbook
        xlWorkBook.Close(false);

        //~~> Quit the Excel Application
        xlApp.Quit();

    }

任何帮助将非常感激。

您需要使用Marshal.GetActiveObject,并且此代码大致正确,但是目前无法测试。

public void RunActualsMacro(string Filepath, string Period, String FiscalYear)
{
    //~~> Define your Excel Objects
    Excel.Application xlApp = null;

    Excel.Workbook xlWorkBook;

    //~~> Start Excel and open the workbook.
    //handle errors below
    try {
        xlApp = (Excel.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    } catch {
        //perhaps exit - or throw??
    }

    xlWorkBook = xlApp.Workbooks["Transactions into LV Template.xlsm"];

    // Populat Cells A1,A2,A3 with string variables
    Excel.Worksheet ws = xlWorkBook.Worksheets["Sheet1"] //what the tab name of sheet
    ws.Cells[1, 1] = Filepath;
    ws.Cells[2, 1] = Period;
    ws.Cells[3, 1] = FiscalYear;


    //~~> Run the macro ControlMacroAct
    xlApp.Run("ControlMacroACT");

    //~~> Clean-up: Close the workbook
    xlWorkBook.Close(false);

    //~~> Quit the Excel Application
    xlApp.Quit();

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM