Skip to content

Latest commit

 

History

History
57 lines (45 loc) · 3.46 KB

how-to-programmatically-copy-worksheets.md

File metadata and controls

57 lines (45 loc) · 3.46 KB
title description ms.date ms.topic dev_langs helpviewer_keywords author ms.author manager ms.subservice
Programmatically copy worksheets
Copy a Microsoft Office Excel worksheet and insert the worksheet copy before or after an existing worksheet in the workbook programmatically from Visual Basic or C#.
02/02/2017
how-to
VB
CSharp
worksheets, copying
Excel [Office development in Visual Studio], copying worksheets
John-Hart
johnhart
mijacobs
office-development

Programmatically copy worksheets

You can create a copy of a worksheet, and insert that worksheet before or after an existing worksheet in the workbook. If you do not specify where to insert the worksheet, Excel creates a new workbook to contain the new worksheet.

[!INCLUDEappliesto_xlalldocapp]

Note

Whether you copy the worksheet programmatically, or the end user copies the worksheet manually, there is no code behind the new worksheet and controls on the new worksheet do not function. This is because the newly copied worksheet is a xref:Microsoft.Office.Interop.Excel.Worksheet object and not a xref:Microsoft.Office.Tools.Excel.Worksheet host item. Windows Forms controls and host controls can only be added to host items. For more information, see Programmatic limitations of host items and host controls.

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

  1. Use the xref:Microsoft.Office.Interop.Excel.Worksheets.Copy%2A method to copy the first worksheet in the current workbook and place the copy after the third sheet.

    :::code language="csharp" source="../vsto/codesnippet/CSharp/Trin_VstcoreExcelAutomationCS/Sheet1.cs" id="Snippet16":::

    :::code language="vb" source="../vsto/codesnippet/VisualBasic/Trin_VstcoreExcelAutomation/Sheet1.vb" id="Snippet16":::

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

  1. Use the xref:Microsoft.Office.Interop.Excel.Worksheets.Copy%2A method to copy the first worksheet in the current workbook and place the copy after the third sheet.

    :::code language="csharp" source="../vsto/codesnippet/CSharp/trin_vstcoreexcelautomationaddin/ThisAddIn.cs" id="Snippet12":::

    :::code language="vb" source="../vsto/codesnippet/VisualBasic/trin_vstcoreexcelautomationaddin/ThisAddIn.vb" id="Snippet12":::

Related content