如何:使用 Visual Studio 项目自动化向工作簿添加工作表

更新:2007 年 11 月

适用对象

本主题中的信息仅适用于指定的 Visual Studio Tools for Office 项目和 Microsoft Office 版本。

项目类型

  • 文档级项目

Microsoft Office 版本

  • Excel 2007

  • Excel 2003

有关更多信息,请参见按应用程序和项目类型提供的功能

此示例向在 Visual Studio 设计器中打开的现有 Microsoft Office Excel 工作簿中添加新工作表。

示例

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

编译代码

此示例有以下要求:

  • 在 Visual Studio 设计器中打开的名为“ExcelWorkbook1”的项目中有一个名为“ExcelWorkbook1”的 Excel 工作簿。在该解决方案中不能有其他项目。

  • 项目中工作簿的格式必须是 Excel 97-2003 工作簿 (.xls)。

  • 创建 ExcelWorkbook1 项目时,请确保未在“新建项目”对话框中选中“创建解决方案的目录”。

可靠编程

在 Visual Studio 宏集成开发环境 (IDE) 中将代码添加到模块中。

清除“选项”对话框中的“总是显示解决方案”选项。若要访问此对话框,请在“工具”菜单上单击“选项”,然后选择“项目和解决方案”文件夹并单击“常规”。

请参见

任务

演练:使用 Visual Studio 项目自动化新建 Office 项目

如何:使用 Visual Studio 项目自动化更改 Excel 属性

概念

Visual Studio Tools for Office 项目扩展性概述

其他资源

Visual Studio Tools for Office 中的项目扩展性