Rodrigo Antunes
Rodrigo Antunes

Reputation: 23

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!

Upvotes: 2

Views: 1282

Answers (3)

UndeadBob
UndeadBob

Reputation: 1129

If your actual code doesn't have more in-between steps, it will always fail. I'm surprised this line didn't error:

Excel.Workbook wb = excel.ActiveWorkbook as Excel.Workbook;

It's because a new instance of Excel does not necessarily create a new workbook. You can check this with the following lines:

Excel.Application application = new Excel.Application();
Excel.Workbooks workbooks = application.Workbooks;
Console.WriteLine(workbooks.Count); // "0"

The new workbook, however, should create the default number of worksheets (usually 3, but editable).

Upvotes: 0

Travis Acton
Travis Acton

Reputation: 4430

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");

Upvotes: 1

Vinicius B
Vinicius B

Reputation: 162

I don't know if you need to get a specific Sheet but if you try this:
Excel.Worksheet ws = wb.Worksheets[1];
It will get the first Sheet of your Workbook

Upvotes: 0

Related Questions