Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Excel Worksheet in C# class file using VSTO

Tags:

c#

excel

vsto

I have created an Excel Addin using the VSTO Template (VS2010, Excel2007). In the Solution Explorer, I have a group called Excel, and under that a file called ExcelAddIn.cs. This has access to the active worksheet through code like

public partial class MyAddIn
{
    Excel.Worksheet activeWorksheet = (Excel.Worksheet)Application.Activesheet;
    Excel.Range firstRow = activeWorksheet.get_Range("A1",missing);
}

etc. This code works fine ie. I can get at the Excel model.

Rather than put all my processing code in this one class file however, I'd like to work on Excel worksheet data in another class file. I have created this file, but am unable to use any code like the above in it, ie. I cannot seem to access the Excel model from this file. I've duplicated the 'using Microsoft.Office.Tools.Excel' references, but putting in a line like:

Excel.Worksheet activeWorksheet = (Excel.Worksheet)Application.Activesheet;

gives me a 'The name 'Application' does not exist in the current context' error.

Any ideas on what references/changes I need to make to get at the Excel model from this separate class file?

btw. The file that works refers to an 'Excel.Application' object for that first code line, the second separate file that doesn't work is referring to 'Microsoft.Office.Interop.Excel' object.

Thanks Pete

==== FOUND ANSWER ==== The way to get at your worksheets from other classes you add is to simply access

Globals.ThisAddIn.Application.ActiveSheet;

for example:

Excel.Worksheet ws = (Excel.Worksheet)Globals.ThisAddin.Application.ActiveSheet;

where 'ThisAddIn' is the name of the class your wizard created (you may have renamed it).

So, use Globals to get at your Excel objects outside the ThisAddin code.

like image 599
Pete855217 Avatar asked Aug 17 '11 11:08

Pete855217


1 Answers

Your own answer here:

The way to get at your worksheets from other classes you add is to simply access

Globals.ThisAddIn.Application.ActiveSheet;

for example:

Excel.Worksheet ws = (Excel.Worksheet)Globals.ThisAddin.Application.ActiveSheet;

where 'ThisAddIn' is the name of the class your wizard created (you may have renamed it).

So, use Globals to get at your Excel objects outside the ThisAddin code.

like image 170
wilsjd Avatar answered Oct 23 '22 10:10

wilsjd