Export (0) Print
Expand All

How to: Add Worksheets to Workbooks Using Visual Studio Project Automation

Note Required applications

The features in this topic are available only if you have the required applications installed.

For more information, see Features Available by Product Combination.

  • One of these development environments:

    VSTO 2005

    -or-

    Visual Studio Team System

  • Microsoft Office 2003

This example adds a new worksheet to an existing Microsoft Office Excel 2003 workbook that is open in the Visual Studio designer.

Example

Sub AddWorksheet()
    ' Find the Visual Studio Tools for Office project.
    Dim vstProject As Project = DTE.Solution.Item(1)

    ' Find the Excel workbook.
    Dim docItem As ProjectItem = _
        vstProject.ProjectItems.Item("ExcelWorkbook1.xls")

    ' Activate the Solution Explorer window.
    Dim solExpl As Window = _
        DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer)
    solExpl.Activate()

    ' Find and select the Excel workbook.
    Dim uiHier As UIHierarchy = solExpl.Object

    ' The path follows the pattern
    ' SolutionName\ProjectName\WorkbookName.
    Dim item As UIHierarchyItem = _
        uiHier.GetItem("ExcelWorkbook1\ExcelWorkbook1.xls")
    item.Select(vsUISelectionType.vsUISelectionTypeSelect)

    ' Execute the shortcut menu command to add a new worksheet.
    Dim commandGuid As String = _
        "{AE97F291-448D-4F9F-93A8-B0D2B78475A4}"

    ' Set commandID to 1 to add a new worksheet, 2 to add a new chart.
    Dim commandID As Integer = 1 
    Dim customIn As Object
    Dim customOut As Object
    DTE.Commands.Raise(commandGuid, commandID, customIn, customOut)
End Sub

Compiling the Code

This example requires:

  • An Excel workbook named ExcelWorkbook1 in a project named ExcelWorkbook1 open in the Visual Studio designer. There must be no other projects in the solution.

Robust Programming

Add the code to a module in the Visual Studio Macros integrated development environment (IDE).

Clear the Always show solution option in the Options dialog box. To access this dialog box, on the Tools menu, click Options, and then select the Projects and Solutions folder and click General.

See Also

Community Additions

ADD
Show:
© 2014 Microsoft