In the event that the initial attempt to retrieve the sheet fails, a crude solution would be to proceed by adding the sheet asynchronously within the .sync()-call:
async function checkedAddSheet() {
Excel.run(async (context) => {
// For debugging:
OfficeExtension.config.extendedErrorLogging = true;
var sheet = context.workbook.worksheets.getItem(NEW_DATA_SHEET_NAME);
sheet.load("name, position");
return context.sync()
.then(function () {
console.log(`Found worksheet named "${sheet.name}" in position ${sheet.position}`);
});
}).then(function () {
console.log("Done");
}).catch(function (error) {
console.error(error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
console.log("Failed to retrieve, proceeding to add...");
addSheet();
});
}
function addSheet() {
Excel.run(async (context) => {
var sheet = context.workbook.worksheets.add(NEW_DATA_SHEET_NAME);
sheet.load("name, position");
return context.sync()
.then(function () {
console.log(`Worksheet named "${sheet.name}" was added in position ${sheet.position}`);
});
}).then(function () {
console.log("Done");
}).catch(function (error) {
console.error(error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
console.log("Failed to retrieve, proceeding to add...");
});
}
Although refinement could involve error type checking, the current function serves its purpose.