I am running a macro code from my C# application. I have placed the Test.xlsm file in the project itself with Properties:
Build Action: Content
Copy to Output Directory: copy always.
However, I get the below exception, when I run the code.
Sorry, we couldn't find Test.xlsm. Is it possible it was moved, renamed or deleted?
I cannot give a hard-coded path since I have to create a clickOnce deployment of this project.
// Define your Excel Objects
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
//Start Excel and open the workbook.
xlWorkBook = xlApp.Workbooks.Open("Test.xlsm");
// Run the macros by supplying the necessary arguments
xlApp.Run("Create", pFilePath1, pPath2);
// Clean-up: Close the workbook
xlWorkBook.Close(false);
// Quit the Excel Application
xlApp.Quit();
I have found the solution. I added Application.StartupPath before the file name:
string workbookPath = Application.StartupPath + @"\Test.xlsm";
//~~> Start Excel and open the workbook.
xlWorkBook = xlApp.Workbooks.Open(workbookPath);