Search code examples
javascriptexceloffice-jsoffice-addinsexcel-addins

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.

This is the error message I get when I try to run this code...

...
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);
...

I'm attempting to create an Excel online add-in using Office JS/Excel API. However, I'm getting an AccessDenied error whilst running the code above. It happens when I attempt to set the locked property, but from other examples I've seen online this looks like the correct way to do it?


Solution

  • The reason to return "AccessDenied" error is due to the sheet is protected. You can revise the code by following ways:

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