Valip
Valip

Reputation: 4650

C# Interop define an array of Worksheets

How can I define an array with 4 worksheets?

For example these are my worksheets:

    var wb = (Excel.Workbook)Globals.ThisAddIn.Application.ActiveWorkbook;
    var wsEvars = wb.Sheets["Evars"];
    var wsProps = wb.Sheets["Props"];
    var wsEvents = wb.Sheets["Events"];
    var wsListVars = wb.Sheets["List Vars"];

And I want to include them in an array as follows:

var sheets = [wsEvars, wsProps, wsEvents, wsListVars];

Upvotes: 1

Views: 1256

Answers (2)

Cool Blue
Cool Blue

Reputation: 6476

With these references...

using Microsoft.Office.Tools.Excel;
using System.Linq;
using Worksheet = Microsoft.Office.Tools.Excel.Worksheet;
using Excel = Microsoft.Office.Interop.Excel;

If you only need com objects you can do...

var wsEvars = wb.Sheets["Evars"];
var wsProps = wb.Sheets["Props"];
var wsEvents = wb.Sheets["Events"];
var wsListVars = wb.Sheets["List Vars"];

var sheets = new Excel.Worksheet[] {wsEvars, wsProps, wsEvents, wsListVars};

If you need the VSTO host interface...

var _factory = Globals.Factory;    

var wsEvars = _factory.GetVstoObject(wb.Sheets["Evars"]);
    var wsProps = _factory.GetVstoObject(wb.Sheets["Props"]);
    var wsEvents = _factory.GetVstoObject(wb.Sheets["Events"]);
    var wsListVars = _factory.GetVstoObject(wb.Sheets["List Vars"]);

    var sheets = new Worksheet[] {wsEvars, wsProps, wsEvents, wsListVars};

Or with linq...

var _sheetsArray = new[]{"wsEvars", "wsProps", "wsEvents", "wsListVars"}.Join(
    _wb.Worksheets.Cast<Excel.Worksheet>(), // outer  
    name => name, s => s.Name,              // key accessors
    (tag, s) => _factory.GetVstoObject(s)   // output selector
).ToArray();

Upvotes: 2

Antonio Pelleriti
Antonio Pelleriti

Reputation: 859

you can declare and initialize an array as follows:

var sheets = new Microsoft.Office.Interop.Excel.Sheets[] { wsEvars, wsProps, wsEvents, wsListVars };

Upvotes: 1

Related Questions