Search code examples
c#excelvstoexcel-addins

C# set opened workbook


I started creating an Excel-Add-IN with C#.

what I need to do is simple, I need to set a workbook to a variable, the workbook is already running, I tried this but did not work

        Excel.Application excel = new Excel.Application();
        Excel.Workbook wb = excel.ActiveWorkbook as Excel.Workbook;
        wb.SaveAs("C:\\Users\\ro_sg\\Desktop\\Pasta1.xlsx");
        Excel.Worksheet ws = wb.Worksheets["Plan1"]; 
        Excel.Range range = ws.Range["A1"];
        range.Value = "Success";

        wb.Save();

The wb variable cannot find the workbook (gets null), and I can't see why.

Please, if any of you spot the mistake let me know.

Thanks!


Solution

  • I believe your issue is it may not be finding the active Excel application upstream from when you set your workbook variable. It appears that your code is trying to create a new excel application (without a workbook) rather than get the existing one that is open.

    Give this a try:

            Excel.Application excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
            Excel.Workbook wb = (Excel.Workbook)excel.ActiveWorkbook;
            wb.SaveAs("D:\\WeeeDueceDuece.xlsx");