如何:使用 Visual Studio 项目自动化向工作簿添加工作表
此示例向在 Visual Studio 设计器中打开的现有 Microsoft Office Excel 工作簿中添加新工作表。
**适用于:**本主题中的信息适用于 Excel 2007 和 Excel 2010 的文档级项目。有关更多信息,请参见按 Office 应用程序和项目类型提供的功能。
示例
Sub AddWorksheet()
' Find the Office project.
Dim vstProject As Project = DTE.Solution.Item(1)
' Find the Excel workbook.
Dim docItem As ProjectItem = _
vstProject.ProjectItems.Item("ExcelWorkbook1.xlsx")
' 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.xlsx")
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 工作簿。 在该解决方案中不能有其他项目。
创建 ExcelWorkbook1 项目时,请确保未在**“新建项目”对话框中选中“创建解决方案的目录”**。
可靠编程
在 Visual Studio 宏集成开发环境 (IDE) 中将代码添加到模块中。
清除**“选项”对话框中的“总是显示解决方案”选项。 若要访问此对话框,请在“工具”菜单上,单击“选项”,然后选择“项目和解决方案”文件夹并单击“常规”**。
请参见
任务
如何:使用 Visual Studio 项目自动化更改 Excel 属性