共用方式為


How to: Programmatically add new worksheets to workbooks

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

You can programmatically create a worksheet and then add the worksheet to the collection of worksheets in the workbook.

Applies to: The information in this topic applies to document-level projects and VSTO Add-in projects for Excel. For more information, see Features available by Office application and project type.

To add a new worksheet to a workbook in a document-level customization

  1. Use the Add method of the Sheets collection.

    Excel.Worksheet newWorksheet;
    newWorksheet = (Excel.Worksheet)Globals.ThisWorkbook.Worksheets.Add();
    
    Dim newWorksheet As Excel.Worksheet
    newWorksheet = CType(Globals.ThisWorkbook.Worksheets.Add(), Excel.Worksheet)
    

    The new worksheet is a native Worksheet object and not a host item. If you want to add a Worksheet host item, you should add the worksheet at design time.

To add a new worksheet to a workbook in a VSTO Add-in

  1. Use the Add method of the Sheets collection.

    Excel.Worksheet newWorksheet;
    newWorksheet = (Excel.Worksheet)this.Application.Worksheets.Add();
    
    Dim newWorksheet As Excel.Worksheet
    newWorksheet = CType(Me.Application.Worksheets.Add(), Excel.Worksheet)
    

    The new worksheet is a native Worksheet object and not a host item. You can also generate a Worksheet host item from the native Worksheet object. For more information, see Extending Word Documents and Excel Workbooks in VSTO Add-ins at Run Time.

See also