如何使Google Sheet中的受保护范围可由App Script中的javascript函数访问



我共享了一个Google Sheets,但保护了某些范围不受编辑。现在,我无法通过应用程序脚本以编程方式编辑范围,例如为单元格设置值。问题:有没有办法保持范围保护(防止用户编辑受保护的范围(并通过脚本进行编辑?非常感谢。

我还没有找到你想要找到的东西,但我想到了一个变通方法,它应该与你想要做的几乎一样。

请尝试通过脚本删除范围保护,然后修改受保护的范围并再次添加保护。

function main() {
// Remove protection before editing
removeProtectionToColumn();
// Call your function that modifies the protected range in between
modifySheetDataFunction(); 
// Add protection again
addProtectionToColumn();
}
function addProtectionToColumn() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange('A:A');
var protectSs = range.protect().setDescription('Protect column A');
var me = Session.getEffectiveUser();
protectSs.addEditor(me);
protectSs.removeEditors(protectSs.getEditors());
if (protectSs.canDomainEdit()) {
protectSs.setDomainEdit(false);
}
}
function removeProtectionToColumn() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
if (protections[i].getDescription() == 'Protect column A') {
protections[i].remove();
}
}
}

这里应该有一个非常小的窗口时间,并且对于你正在尝试的任何工作都是可行的,除非你正在修改一组非常非常大的数据。你可以随时与同事一起测试这种行为。

有关保护的更多详细信息,请参阅本文档

最新更新