0

我有一个脚本,可以复制现有工作表并在这个新工作表中生成一个名为Lists.

寻找一种在脚本再次运行时删除新工作表的方法,但我不断收到“工作表激活:请求的资源不存在”错误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();

4

1 回答 1

3

我建议使用可选的链接运算符 (?.)。

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();
}

请参考以下链接。

  1. https://docs.microsoft.com/en-us/office/dev/scripts/develop/best-practices#verify-an-object-is-present
  2. https://github.com/sumurthy/officescripts-projects/tree/main/Top%205%20Tips
于 2021-06-17T08:36:06.167 回答