如何删除存在的工作表并使用 Office 脚本创建同名的新工作表
How to delete a worksheet if it exists and create a new worksheet with the same name with Office Scripts
我有一个脚本可以复制现有工作表并在这个名为 Lists
的新工作表中生成一个 table。
正在寻找每当脚本再次运行时删除新工作表的方法,但我不断收到“工作表激活:请求的资源不存在”错误 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();
我建议使用可选的链接运算符 (?.)。
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();
}
请参考以下内容link。
我有一个脚本可以复制现有工作表并在这个名为 Lists
的新工作表中生成一个 table。
正在寻找每当脚本再次运行时删除新工作表的方法,但我不断收到“工作表激活:请求的资源不存在”错误 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();
我建议使用可选的链接运算符 (?.)。
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();
}
请参考以下内容link。