I have a script that makes a copy of an existing worksheet and generates a table within this new worksheet called Lists
.
Looking for a way to delete the new worksheet whenever the script runs again, but I keep getting the 'Worksheet activate: The requested resource doesn't exist' error with selectedSheet.activate();
let selectedSheet = workbook.getWorksheets()[0];
selectedSheet.getAutoFilter().remove();
// Duplicate worksheet.
let itemsName = "Lists";
let sheetItem = workbook.getWorksheet(itemsName);
// If `null` wasn't returned, then there's already a worksheet with the same name.
if (sheetItem) {
console.log(`Worksheet ${itemsName} already exists. Deleting...`);
// Delete the sheet.
sheetItem.delete();
} else {
let selectedSheet = workbook.getWorksheets()[0];
}
selectedSheet.activate();
let itemsSheet = selectedSheet.copy(ExcelScripWorksheetPositionType.before, selectedSheet);
itemsSheet.setName("Lists");
itemsSheet.activate();
I suggest to use the optional chaining operator (?.).
function main(workbook: ExcelScript.Workbook)
{
const itemsName = "Lists";
workbook.getWorksheet(itemsName)?.delete();
const selectedSheet = workbook.getFirstWorksheet();
const itemsSheet = selectedSheet.copy(ExcelScript.WorksheetPositionType.before, selectedSheet);
itemsSheet.setName(itemsName);
itemsSheet.activate();
}
Please refer to the below link.