簡體   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