Skip to content

Copy a worksheet

This article explains how to use Office Scripts to copy a specific worksheet.

Use the copy method of the Worksheet object.

Method details
/**
* @param positionType Where to place the copied sheet (choose from ExcelScript.WorksheetPositionType)
* @param relativeTo The reference worksheet when positionType is before or after
* @return The copied worksheet object
*/
ExcelScript.Worksheet.copy(
positionType?: WorksheetPositionType,
relativeTo?: Worksheet
): ExcelScript.Worksheet;

Both arguments are optional. The default value of positionType is none, and if you omit the arguments, the copied sheet is placed at the beginning of the workbook.

For positionType, specify one of none, before, after, beginning, or end. If you specify before or after, specify the reference worksheet in relativeTo.

This sample code specifies the name of the sheet to copy and places the copy right after that worksheet.

If the specified sheet isn’t found, it throws an error.

Sample that copies a worksheet
function main(workbook: ExcelScript.Workbook) {
/** Target sheet name */
const sheetname = 'Sheet1';
/** Target worksheet */
const sheet = workbook.getWorksheet(sheetname);
if (!sheet) {
throw `There is no worksheet named ${sheetname}`;
}
const copied = sheet.copy(ExcelScript.WorksheetPositionType.after, sheet);
console.log(`Copied ${sheetname}.`, `Name of the copied sheet: ${copied.getName()}`);
}