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

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

所有,

道歉,如果这是一个非常基本的问题,并已被要求之前,我主要写VBA / JAVA。但是一个项目我的工作需要一个C#脚本。其中中进行3个简单的步骤:

  1. 一个目标Excel工作簿是已经打开。文件路径: \ Csdatg04 \ psproject \机器人\仁科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();

    }

任何帮助将非常感激。

c# excel excel-interop
1个回答
1
投票

您需要使用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();

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