【问题标题】:How to make a protected range in Google Sheet accessible for a javascript function from App Script如何使 Google Sheet 中的受保护范围可用于 App Script 中的 javascript 函数
【发布时间】:2021-01-05 22:36:23
【问题描述】:

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

【问题讨论】:

    标签: google-apps-script google-sheets


    【解决方案1】:

    我没有找到您要查找的内容,但我想到了一种解决方法,该解决方法应该与您尝试执行的操作几乎相同。

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

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

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

    有关保护的更多详细信息,请参阅documentation

    【讨论】:

    • 感谢您的回答!我有一个小问题。通过按下侧边栏上的按钮调用修改其间受保护范围的函数,它将用户表单条目作为参数(数组)并在受保护范围上设置相同的数组。所以,它写成 modifySheetDataFunction(array);当我将其他两个函数放入此函数(modifySheetDataFunction(array))并调用它们时,除了数组出现在不受保护的范围内之外,什么也没有发生。而且,我无法通过按下按钮调用函数 main 并将数组作为参数发送。任何见解将不胜感激!
    • 默认情况下,保护只适用于其他用户,不会影响添加它的用户,在这种情况下,您和您运行的脚本仍然可以手动编辑工作表,即使范围已经受到保护。您可以尝试使用其他用户在隐身模式下对其进行编辑,以查看应用的保护是否有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多