Mike B
Mike B

Reputation: 2672

How do I display a worksheet by name using VSTO 2010 for Excel

I have never used VSTO and I am finding it difficult to find a good learning aid for 2010.

My need is simple, I have a business workbook with 42 worksheets (I orignally guessed 20 but after counting found a surprising number). I want to add a ribbon (That part is easy) using VSTO to allow employees to navigate the large number of pages easily. I cannot seem to find the c# code to display a specific worksheet (Preferably by name) that I can simply add to the click event of the buttons.

Thanks

Upvotes: 6

Views: 5587

Answers (1)

Richard Cook
Richard Cook

Reputation: 33089

Call the Activate method on the worksheet object (of type Microsoft.Office.Tools.Excel.Worksheet).

You can do this by name from within your ThisWorkbook class or via Globals.ThisWorkbook as follows:

private Excel.Worksheet GetWorksheetByName(string name)
{
  foreach (Excel.Worksheet worksheet in this.Worksheets)
  {
    if (worksheet.Name == name)
    {
      return worksheet;
    }
  }
  throw new ArgumentException();
}

private void ActivateWorksheetByName(string name)
{
  GetWorksheetByName(name).Activate();
}

Call the ActivateWorksheetByName and pass the name of the worksheet to show.

Upvotes: 11

Related Questions