为什么我尝试锁定或解锁 Excel API 中的一系列单元格时出现 AccessDenied

Why do I get AccessDenied when attempting to lock or unlock a range of cells in Excel API

Error: AccessDenied: You cannot perform the requested operation.

这是我尝试 运行 此代码时收到的错误消息...

...
var sheet = context.workbook.worksheets.getActiveWorksheet();
var entireRange = sheet.getRange();

entireRange.load(['address', 'format/protection/locked']);
sheet.load('protection/protected');
return context.sync()
    .then(
        function() {
            if (sheet.protection.protected) {
                sheet.protection.unprotect();
            } else {
                sheet.protection.protect();
                console.log(entireRange.format.protection.locked);
                entireRange.format.protection.locked = true;
            }
        }
    )
    .then(context.sync);
...

我正在尝试使用 Office JS/Excel API 创建 Excel 在线加载项。但是,我在 运行 上面的代码中遇到了 AccessDenied 错误。当我尝试设置锁定 属性 时会发生这种情况,但从我在网上看到的其他示例来看,这似乎是正确的方法吗?

return "AccessDenied" 错误的原因是 sheet 受到 保护。您可以通过以下方式修改代码:

    1. Move "entireRange.format.protection.locked = true" before "sheet.protection.protect()"

    Or

    2. Allow format cells when sheet is protected
    sheet.protection.protect({
        allowFormatCells: true
    });